Skip to content

Instantly share code, notes, and snippets.

@ucheng
Created July 18, 2012 06:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ucheng/3134548 to your computer and use it in GitHub Desktop.
Save ucheng/3134548 to your computer and use it in GitHub Desktop.
Add or Update Json field value
package com.stanley;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectReader;
public class ReadStringToJsonNodeAndUpdateIt {
public static void main(String[] args) {
ObjectMapper mapper = new ObjectMapper();
ObjectReader reader = mapper.reader();
String jsonString = "{\"users\" : [{\"id\" : \"1\", \"name\" : \"stanley\", \"age\" : \"28\" }]}";
try {
JsonNode node = reader.readTree(jsonString);
System.out.println(node.toString());
ObjectNode objectNode = (ObjectNode) node;
objectNode.put("gender", "male");
System.out.println(node.toString());
} catch (JsonProcessingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@gourav999
Copy link

is this json saving after updating?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment