Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read part of a JSON String using Jackson

Tags:

The JSON string is as follows

{    "rank":"-text_relevance",    "match-expr":"(label 'star wars')",    "hits":{       "found":7,       "start":0,       "hit":[          {"id":"tt1185834",              "data":{                 "actor":["Abercrombie, Ian","Baker, Dee","Burton, Corey"],                 "title":["Star Wars: The Clone Wars"]              }          },          .          .          .          {"id":"tt0121766",              "data":{                 "actor":["Bai, Ling","Bryant, Gene","Castle-Hughes, Keisha"],                 "title":["Star Wars: Episode III - Revenge of the Sith"]              }          }        ]     },     "info":{        "rid":"b7c167f6c2da6d93531b9a7b314ad030b3a74803b4b7797edb905ba5a6a08",        "time-ms":2,        "cpu-time-ms":0     }     }  

It has many fields, but I just have want the Data field. This won't work:

mapper.readvalue(jsonString,Data.class);  

How do I make Jackson read just the "Data" field?

like image 507
gnjago Avatar asked Jul 26 '12 20:07

gnjago


People also ask

How do you parse JSON strings into Jackson JsonNode model?

The process of parsing JsonString into JsonNode is very simple. We simply create an instance of ObjectMapper class and use its readTree() method in the following way: String str = "{\"proId\":\"001\",\"proName\":\"MX Pro 20\",\"price\":\"25k\"}"; ObjectMapper map = new ObjectMapper();

How do I read a JSON file using ObjectMapper?

Read JSON file into Object using ObjectMapper. To read JSON file into java object, Jackson provides ObjectMapper. readValue(). Find the input JSON file. Now find the java class to read the JSON.


1 Answers

Jackson 2.3 now has a JsonPointer class you can use. There's a simple example in their quick overview for the release.

Usage is simple: for JSON like

{     "address" : { "street" : "2940 5th Ave", "zip" : 980021 },        "dimensions" : [ 10.0, 20.0, 15.0 ]  } 

you could use expressions like:

  JsonNode root = mapper.readTree(src);    int zip =root.at("/address/zip").asIntValue();    double height = root.add("/dimensions/1").asDoubleValue();// assuming it's the second number in there 
like image 177
catorda Avatar answered Oct 20 '22 13:10

catorda