Skip to content

Instantly share code, notes, and snippets.

@tekmark
Last active October 10, 2017 18:22
Show Gist options
  • Save tekmark/bc001f6280d737e80b58211830fb7b7f to your computer and use it in GitHub Desktop.
Save tekmark/bc001f6280d737e80b58211830fb7b7f to your computer and use it in GitHub Desktop.
[JSON <-> Java Object] JSON Reading and Writing Using ObjectMapper #jackson #spring #spring_boot #json
// jackson package
//JSON to Java
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
ObjectMappper mapper = new ObjectMapper();
// readValue throws IOException, com.fasterxml.jackson.core.JsonParseException,
// JsonMappingException
JavaObject object = mapper.readValue(json, JavaObject.class);
//Java to JSON
String jsonStr = mapper.writeValueAsString(object);
//JSON array to Java List
String jsonCarArray =
"[{ \"color\" : \"Black\", \"type\" : \"BMW\" }, { \"color\" : \"Red\", \"type\" : \"FIAT\" }]";
List<Car> listCar = objectMapper.readValue(jsonCarArray, new TypeReference<List<Car>>(){});
//JSON to Java map
String json = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Map<String, Object> map = objectMapper.readValue(json, new TypeReference<Map<String,Object>>(){});
// JsonNode
String json = "{ \"color\" : \"Black\", \"type\" : \"FIAT\" }";
JsonNode jsonNode = objectMapper.readTree(json);
String color = jsonNode.get("color").asText();
// JSON Array to POJO List
String jsonStr = "[{\"first\": \"alex\", \"last\": \"hou\"}," +
"{\"first\": \"mike\", \"last\": \"xie\"}]";
ObjectMapper mapper = new ObjectMapper();
List<People> peopleList = mapper.readValue(jsonStr,
mapper.getTypeFactory().constructCollectionType(List.class, People.class));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment