Reputation: 1
I am new Jackson. I want to append a new class object with the existing json object. Below is json file and i my java code
Responder.json File
[{ "ip": "10.17.16.56", "status": "Registered", "registeredAt": "18:49 AM IST, Mon, Sep 12th 2016", "managedClusters": 2 }, { "ip": "10.17.16.57", "status": "Pending", "registeredAt": "18:49 AM IST, Mon, Sep 13th 2016", "managedClusters": 3 }, { "ip": "10.17.16.58", "status": "UnRegistered", "registeredAt": "18:49 AM IST, Mon, Sep 14th 2016", "managedClusters": 2 }, { "ip": "10.17.16.59", "status": "Suspended", "registeredAt": "18:49 AM IST, Mon, Sep 15th 2016", "managedClusters": 3 }]
Java method:
I have written the below method to add a new object, but i am sure it is not the right way as i am getting class cast exception when converting the JsonNode variable to ObjectNode variable.
static void jsonOperation() throws JsonProcessingException, IOException {
ObjectMapper mapper = new ObjectMapper();
JsonNode root =mapper.readTree(new File("/opt/jetty/ucod/data/ss/Responders_dummy.json"));
System.out.println("json : "+mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root));
ObjectNode newNode = mapper.createObjectNode();
newNode.put("ip", "10.197.93.62");
newNode.put("status", "Success");
newNode.put("registeredAt", "10/12/2017");
newNode.put("managedClusters", "4");
((ObjectNode)root).set("", newNode); //Getting class cast exception here
}
Could some one help to appending new object to existing json file using jackson (Instead of reading the json object from file and appending the new object and overwriting the file again)?
Thanks in advance for your help.
Upvotes: 0
Views: 1446