0

I have a JSON file name abc.json Once I opened this file there is data like in square brackets.

[{
"1" : "xxx",
"20" : "ppp",
"25" : "hhh"
}]

Here in this keys are not known. I want to add new key-value pairs, update values according to some key-value and delete some fields. I have to use com.google.code library.

6
  • stackoverflow.com/questions/43255577/… Commented May 28, 2021 at 4:20
  • That's great... Also can you tell me how to add new field in same JSON file which should maintain square brackets as opening and closing? Thanks in advance Commented May 28, 2021 at 4:30
  • Why do you want to update the JSON file? This is a non-standard use of JSON. If you are storing data, you should consider using a database, such as SQLite or Realm, instead of a JSON file. Commented May 28, 2021 at 5:01
  • Also note that if this JSON file is stored in res or asset in your Android Studio package, you cannot update it anyway. (At least not easily) Commented May 28, 2021 at 5:02
  • That's the correct point by @Code-Apprentice. But as it was asked by one of my friend whose organization given a task like this. They are using Java to build API. Could you please provide any way? Thanks in advance. Commented May 28, 2021 at 5:23

1 Answer 1

0

As said already in comments, there are some flaws in this architecture.

However, as a json object is basically a Map in java, you can use jackson lib to deserialize the json, add a value in the map and serialize it again with jackson. See the code below :

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;


class ObjectMapperTest {


    @Test
    void test_json_array_of_map() throws JsonProcessingException {
        String jsonAsString = "[{\"1\":\"xxx\",\"20\":\"ppp\",\"25\":\"hhh\"}]";

        ObjectMapper objectMapper = new ObjectMapper();
        List<Map<String,String>> deserialized = objectMapper.readValue(jsonAsString, new TypeReference<>() {
        });
        deserialized.get(0).put("myNewKey", "myNewValue");

        System.out.println(objectMapper.writeValueAsString(deserialized));
    }

}

This gives you the following output :

[{"1":"xxx","20":"ppp","25":"hhh","myNewKey":"myNewValue"}]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.