Thursday, September 20, 2018

JAVA-JSON Serialization & Deserialization Using JACKSON

Converting JSON String to MAP


try {
   ObjectMapper mapper = new ObjectMapper();
   String json = "{\"JSON\":{\"type\":\"ID\",\"value\":\"vvv\"},\"info\": \"Yes\"}";
   Map<String, Object> map = new HashMap<String, Object>();
   // convert JSON string to Map
   map = mapper.readValue(json, new TypeReference<Map<String, Object>>(){});
   System.out.println("CONVERTING JSON STRING TO MAP--="+map);

  } catch (JsonGenerationException e) {
   e.printStackTrace();
  } catch (JsonMappingException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }


Converting MAP to JSON String


ObjectMapper mapper2 = new ObjectMapper();
  Map<String, Object> carMap = new HashMap<String, Object>();
  carMap.put("car", "Audi");
  carMap.put("price", "30000");
  carMap.put("model", "2010");
  List<String> colors = new ArrayList<String>();
  colors.add("Grey");
  colors.add("White");
  colors.add("Black");
  carMap.put("colors", colors);
  try {
   String jsonString = new ObjectMapper().writeValueAsString(carMap);
   System.out.println("Convert Map to JSON String=="+jsonString);
  } catch (JsonProcessingException e) {
   e.printStackTrace();
  }


Converting MAP to JSON Object


try {
   JSONObject jsonObject = new JSONObject(carMap);
   System.out.println("Convert Map to JSON Object=="+jsonObject);
  } catch (Exception e) {
   e.printStackTrace();
  }


Converting JSON Object to MAP

try {
   String jsonjsonString = "{\"JSON\":{\"type\":\"ID\",\"value\":\"vvv\"},\"info\": \"Yes\"}";
   ObjectMapper mapper12 = new ObjectMapper();
   JsonNode jsonNode = mapper12.readTree(jsonjsonString);
   Map<String, Object> mapp = new HashMap<String, Object>();
   mapp = convertJSONObjectToMap(jsonNode);
   System.out.println("Convert JSON Object to Map =="+mapp);
  } catch (Exception e) {
   e.printStackTrace();
  }


Output :




No comments:

Post a Comment