0

My Json is like this

{
  "A1":"1234",
  "A2": "123",   
  "A3": "???",
  "A4": "object, may not be populated.",
  "A5": { },
  "A6": { },
  "A7":{
    "B1": ["100"],
    "B2": ["C"],
    "B3": ["O", "A"]
},
  "A8":{
      "B4":["D1"],
      "B5":["D2"],
      "B6":["D3"],
      "B7":["D4"],
      "B8":["D5"],
      "B9":["D6"],
      "B10":["123"]
    }
  "ignoreThisField": "it is useless"
}

I am using Jackson library. I want to edit let's say element B4, which is inside A8 and it is of array type. I tried below code

    byte[] jsonData = readJson(JsonFilePath);

    // Convert json String to object

    POJOClass pojo= getValue(jsonData, POJO.class);

    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true)
            .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, true);

    JsonNode rootNode = objectMapper.readTree(jsonData);
    // ((ObjectNode) rootNode).put("B4", "A" + "Somedata");

But it gives me output as

"B4":"[Somedata]"

instead of

"B4":["Somedata"]

which results in unexpected result.
B4 node contains list of data. How can we edit a node which is type array. If we can not achieve this using jackson then is there any other library which can solve the problem?
I tried below links
Modify JsonNode of unknown JSON dynamically in Java and How to retrieve and update json array element without traversing entire json but could not achieve much out of it

SachinB
  • 348
  • 6
  • 18

2 Answers2

1

If i am not wrong you want to modify the B4 object present in the JSON data. To correctly do it you should use the below code.

        JsonNode node = rootNode.get("A8");
        List<String>list = new ArrayList<String>();//create a ArrayList
        list.add("Anything"); //add data to arraylist 
        ArrayNode arrayNode = ((ObjectNode)node).putArray("B4"); //add the arraydata into the JSONData
        for (String item : list) { //this loop will add the arrayelements one by one.
            arrayNode.add(item);
        }
Rishal
  • 1,480
  • 1
  • 11
  • 19
0

you not using jackson lib fully.

<YOur pojo object> mypojo =objectMapper.readValue(jsonData, <yourpojo.class>);

now you can just use getter setter

Ben
  • 54
  • 4
  • I am doing that and using setter method I tried to set the value of particular node but it did not workout – SachinB Apr 05 '18 at 12:33
  • i am really interested to know about same ? will you mind to share your pojo ? you can surely use Node but there are easy ways to go such. – Ben Apr 05 '18 at 12:49