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.

3
  • Exception? You didn't think contents of that exception might be useful? :-) Commented Mar 24, 2016 at 23:47
  • No? Would be happy to hear your ideas ... :-) Commented Mar 29, 2016 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. Commented Mar 30, 2016 at 2:42

1 Answer 1

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".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.