2

I have a nested json structure:

"info": [
       {
        "name":"Alice",
        "phone": [{
            "home": "1234567890",
            "mobile": "0001112223"
        }]
    },
    {
        "name":"Bob",
        "phone": [{
            "home": "3456789012",
            "mobile": "4445556677"
        }]
    }
]

I'm using jackson. I only want to extract the information about "Bob" and read it into a tree. I do not want to read the whole structure into the tree (I know how to do that) and then extract the information on Bob. I'd like to use the streaming API (JsonParser) to first extract all the information with "Bob" and then make that into a jsontree.

I thought I'd read it into a byte array and then convert that into a tree like so:

JsonToken token = null;
byte[] data;
int i = 0;

while( jParser.nextToken()!=JsonToken.END_ARRAY) {
    data[i] = jParser.getByteValue();
    i ++;
}
JsonNode node = null;
ObjectMapper objectMapper = new ObjectMapper();

try {
    node = objectMapper.readValue(jParser, JsonNode.class);
    }
catch(Exception e) {
    e.printStackTrace();
}

However, this is not returning the result I want. There's a jsonParse exception so I think this isn't the way to go.

John
  • 53
  • 1
  • 6
  • Exception? You didn't think contents of that exception might be useful? :-) – StaxMan Mar 24 '16 at 23:47
  • No? Would be happy to hear your ideas ... :-) – John Mar 29 '16 at 20:49
  • What I meant was that without exception message there is no way to know what is happening. Code would look legit. But I do have better coding idea too, will add an answer. – StaxMan Mar 30 '16 at 02:42

1 Answers1

1

Use of JSON pointer should work here. Functionally, reading it as JsonNode, extracing could look something like:

JsonNode stuff = mapper.readTree(source).at("/info/1");

but you can also get it without reading it all in with

JsonNode stuff = mapper.reader().at("/info/1").readTree(source);

or whatever path expression you want. Note, however, that unlike with XPath (et al) you can not use filtering of sub-trees to check (for example) that "name" property of Object to read matches "Bob".

StaxMan
  • 113,358
  • 34
  • 211
  • 239