Last active
October 10, 2017 18:22
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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