2

Hi I have a Json like follows:

A {
    B {
        C [{
            x1:x2,
            y1:y2
          }]
       }
  }   

Now my requirement is to convert the A, B, C to camelCase notation(as required) which I did by using @JsonProperty and getter and setter methods for the respective POJO class.

Finally, my output is as follows:

a {
    b {
        c [{
            x1:x2,
            y1:y2
          }]
       }
  }   

Now I want to add a new empty object like d between b and c.

Can you please help me in appending a new empty JSON object.

The required output should be something like this:

a {
    b {
       d {
          c [{
            x1:x2,
            y1:y2
          }]
       }
     }
  }

Json :

"Skills" : {
  "SkillSet" : [ 
    {
        "Skill" : "Management"
    },
    {
        "Skill" : "IT"
    }, 
  ]
}

I need something like this:

"skills" : {
  "mainSkills" {
     "skillSet" : [ 
       {
        "Skill" : "Management"
       },
       {
        "Skill" : "IT"
       }, 
     ]
   }
}

I'm done with converting the camelCase but I need to insert the new object "mainSkills".

Pavan
  • 543
  • 4
  • 16

1 Answers1

1

The following will give you the expected output:

String json = "{\n" +
              "  \"skills\": {\n" +
              "    \"skillSet\": [\n" +
              "      {\n" +
              "        \"skill\": \"Management\"\n" +
              "      },\n" +
              "      {\n" +
              "        \"skill\": \"IT\"\n" +
              "      }\n" +
              "    ]\n" +
              "  }\n" +
              "}";

// Create ObjectMapper instance to parse the JSON
ObjectMapper mapper = new ObjectMapper();

// Parse the JSON into the Jackson tree model
JsonNode tree = mapper.readTree(json);

// Store a reference to the "skills" node
JsonNode skills = tree.get("skills");

// Store a reference to the "skillsSet" node
JsonNode skillSet = skills.get("skillSet");

// Remove the "skillsSet" node from the tree
((ObjectNode) skills).remove("skillSet");

// Create the "skillSet" node under "mainSkills" 
// and sets it under the "skills" node
((ObjectNode) skills).set("mainSkills", 
        mapper.createObjectNode().set("skillSet", skillSet));

// Write the tree as a JSON string using the default pretty printer
String newJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(tree);

If you don't want to manipulate the JSON as demonstrated above, follow the JB Nizet approach.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359