Tuesday 17 March 2020

Jackson: Parse Json String using JsonNode

Below statements are used to get JsonNode from a json string.  
String json = "...";
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode = mapper.readTree(json);

Once you got JsonNode object, you can use it to parse the json string.

App.java
package com.sample.app;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

  public static void main(String args[]) throws JsonProcessingException, IOException {
    String json = "{\n" + "  \"firstName\" : \"Krishna\",\n" + "  \"lastName\" : \"Gurram\"\n" + "}";

    ObjectMapper mapper = new ObjectMapper();
    JsonNode jsonNode = mapper.readTree(json);

    JsonNode firstNameNode = jsonNode.get("firstName");
    JsonNode lastNameNode = jsonNode.get("lastName");

    System.out.println("First Name : " + firstNameNode.textValue());
    System.out.println("Last Name : " + lastNameNode.textValue());
  }

}

Output
First Name : Krishna
Last Name : Gurram


Previous                                                    Next                                                    Home

No comments:

Post a Comment