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.

Reza Ebrahimpour
  • 814
  • 6
  • 20
Aman BL
  • 1
  • 1
  • https://stackoverflow.com/questions/43255577/parse-json-with-unknown-key/43255611#43255611 – IntelliJ Amiya May 28 '21 at 04: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 – Aman BL May 28 '21 at 04: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. – Code-Apprentice May 28 '21 at 05: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) – Code-Apprentice May 28 '21 at 05: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. – Aman BL May 28 '21 at 05:23
  • If you are building an API, you don't need to save the a JSON file. Typically you build up an object then serialize it to JSON directly to the HTTP response. Any modifications should be made to the Java objects before serializing them. – Code-Apprentice May 28 '21 at 19:59

1 Answers1

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"}]