-1

im stuck at trying to update .json from java app.

theres only one method from it when using ObjectMapper but cant figure out parameters.

first parameter is object to update but i have no idea how to pass it? i mean, its in file. second and last parameter i have no idea what it is supposed to be. ive read docs but still- no idea what they want there.

secondly, my other approach was to just rewrite whole .json but then i couldnt write more than one person into it (my json is Person (people) database - it has few fields within each "object"). again tried more stuff (eg putting 10 people into List and putting this list object (instance) into .json but still only one person is there. it requires Object parameter.

please help me :)))

  • Please provide the sample json and sample code what you have tried so far to get clear understanding of your question – Pramod Jul 03 '21 at 17:34

1 Answers1

-1

There are 3 main libraries to deal with json

  1. json-simple.jar

ex:

List arr = new ArrayList();  
arr.add("sonoo");    
arr.add(new Integer(27));    
arr.add(new Double(600000));   
String jsonText = JSONValue.toJSONString(arr);  

2nd by using gson library

new Gson().toJson(arr);

3rd by using jackson

    ObjectMapper mapper = new ObjectMapper();

    ArrayNode arrayNode = mapper.createArrayNode();

    /**
     * Create three JSON Objects objectNode1, objectNode2, objectNode3
     * Add all these three objects in the array
     */

    ObjectNode objectNode1 = mapper.createObjectNode();
    objectNode1.put("bookName", "Java");
    objectNode1.put("price", "100");

    ObjectNode objectNode2 = mapper.createObjectNode();
    objectNode2.put("bookName", "Spring");
    objectNode2.put("price", "200");

    ObjectNode objectNode3 = mapper.createObjectNode();
    objectNode3.put("bookName", "Liferay");
    objectNode3.put("price", "500");

    /**
     * Array contains JSON Objects
     */
    arrayNode.add(objectNode1);
    arrayNode.add(objectNode2);
    arrayNode.add(objectNode3);

    /**
     * We can directly write the JSON in the console.
     * But it wont be pretty JSON String
     */
    System.out.println(arrayNode.toString());

    /**
     * To make the JSON String pretty use the below code
     */
       System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode));
anish sharma
  • 568
  • 3
  • 5