Bob
Bob

Reputation: 1625

How can I parse a JSON object with unknown keys?

I'm currently getting back json from a third party API that looks like this

{
    success: true,
    data: {
        acdc-key1: [{
            id: acdc-key1,
            othervar: stuff,
            foo: bar
        }],
        r2d2-key2: [{
            id: r2d2-key2,
            othervar: thing,
            foo: mu
        }]
    }
}

etc..

Basically it's an object which has an object, which has keys, and those keys have arrays of objects.

I'm using mapper to convert the response from the API into JAva objects, but I'm not sure how to construct my class so that it can be mapped properly.

The main problem is the long array of keys that will always change and aren't set fields.

Upvotes: 1

Views: 3717

Answers (2)

vach
vach

Reputation: 11377

You can always get a Map object from any json using for example Gson (googles library). And get from that map only those keys that you know for sure that are there...

Upvotes: 0

Ashley Frieze
Ashley Frieze

Reputation: 5443

You could use Jackson and create a JSON parse tree with it instead. This would be a set of java objects that represent the JSON but as a tree of objects and properties, rather than POJOs.

Then you can traverse the tree to find properties you're particularly interested in. You could even create a wrapper class which has the getters and setters for properties you are interested in, but internally uses the tree of objects to access the values in the raw JSON.

There seems to be a related question here - How do you tree walk JSON via Jackson 2 JsonNode?

Upvotes: 3

Related Questions