JsonNode as output type of DocumentContext.read()

467 views
Skip to first unread message

chefho...@gmail.com

unread,
Nov 7, 2015, 7:37:47 AM11/7/15
to JsonPath
I'm new to this JsonPath library, and can't really tell from the documentation how to work with the results of read operations.

I don't need to convert results into pojos, but I would like to work with the results as jackson JsonNodes, for example.

Given something like this:

{
   "bradies": [
      { "name": "bobby", "gender": "male" }
      { "name": "greg", "gender": "male" }
      { "name": "cindy", "gender": "female" }
      { "name": "marsha", "gender": "female" }
   ]
}

...I'd like to be able to do something like this:

Filter girlsOnly = filter( where("gender").is("female") );
List<JsonNode> bradyGirls = parseResults.read( "$.bradies", girlsOnly );

...but, accessing elements of the list above yields a ClassCastException.

Is it possible to get results from read() returned as jackson objects?

kalle stenflo

unread,
Nov 7, 2015, 3:16:16 PM11/7/15
to JsonPath
Yes it's possible. Try something like this.

 
@Test
public void using_jackson_json_node_provider() {


   
//Configure this when your application bootstraps
   
Configuration.setDefaults(new Configuration.Defaults() {
       
@Override
       
public JsonProvider jsonProvider() {
           
return new JacksonJsonNodeJsonProvider();
       
}


       
@Override
       
public Set<Option> options() {
           
return EnumSet.noneOf(Option.class);
       
}


       
@Override
       
public MappingProvider mappingProvider() {
           
return new JacksonMappingProvider();
       
}
   
});


   
String json = "{\n" +
           
"   \"bradies\": [\n" +
           
"      { \"name\": \"bobby\", \"gender\": \"male\" },\n" +
           
"      { \"name\": \"greg\", \"gender\": \"male\" },\n" +
           
"      { \"name\": \"cindy\", \"gender\": \"female\" },\n" +
           
"      { \"name\": \"marsha\", \"gender\": \"female\" }\n" +
           
"   ]\n" +
           
"}";


   
Filter girlsOnly = Filter.filter(Criteria.where("gender").is("female"));
    com
.fasterxml.jackson.databind.node.ArrayNode result1 = JsonPath.parse(json).read("$.bradies[?]", girlsOnly);


   
//this is equivalent (using inline filter)
    com
.fasterxml.jackson.databind.JsonNode result2 = JsonPath.parse(json).read("$.bradies[?(@.gender == 'female')]");


   
System.out.println(result1);
   
System.out.println(result2);
}



Reply all
Reply to author
Forward
0 new messages