Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jackson to manually parse JSON

Tags:

java

json

jackson

Is it possible to use Jackson library to manually parse JSON?

I.e. I don't want to use ObjectMapper and convert JSON to some object, but rather I want select some individual properties from JSON, like in XPath:

For example this is my JSON:

{
  "person": {
      "name": "Eric",
      "surname": "Ericsson",
      "address" {
         "city": "LA",
         "street": "..."
       } 
   }
}

And all what I want is just to get Name and the City, for this cases I don't want introduce 2 new Java classes (Person and Address) and use them with ObjectMapper, but I'm just want to read this values like in xPath:

Pseudocode:

String name = myJson.get("person").get("name")
String city = myJson.get("person").get("address").get("city")
like image 749
WelcomeTo Avatar asked Mar 15 '23 22:03

WelcomeTo


2 Answers

You can use the Jackson tree model and JsonNode#at(...) method which takes the Json Pointer expression as a parameter.

Here is an example:

public class JacksonJsonPointer {
    static final String JSON = "{"
            + "  \"person\": {"
            + "      \"name\": \"Eric\","
            + "      \"surname\": \"Ericsson\","
            + "      \"address\": {"
            + "         \"city\": \"LA\","
            + "         \"street\": \"...\""
            + "       }"
            + "   }"
            + "}";

    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode json = mapper.readTree(JSON);
        System.out.println(json.at("/person/name"));
        System.out.println(json.at("/person/address/city"));
    }
}

Output:

"Eric"
"LA"
like image 139
Alexey Gavrilov Avatar answered Mar 17 '23 10:03

Alexey Gavrilov


Yes Using Json parser you can parse your Json, Below is a sample example you can find more in jackson documentation

     JsonParser jsonParser = new JsonFactory().createJsonParser(jsonStr);
     while(jsonParser.nextToken() != JsonToken.END_OBJECT){
         String name = jsonParser.getCurrentName();
         if("name".equals(name)) {
             jsonParser.nextToken();
             System.out.println(jsonParser.getText());
         }
         if("surname".equals(name)) {
             jsonParser.nextToken();
             System.out.println(jsonParser.getText());
         }
         if("city".equals(name)) {
             jsonParser.nextToken();
             System.out.println(jsonParser.getText());
         }
     }
like image 42
Naveen Ramawat Avatar answered Mar 17 '23 11:03

Naveen Ramawat