1

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.

Bob
  • 1,605
  • 2
  • 18
  • 33

2 Answers2

3

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?

Community
  • 1
  • 1
Ashley Frieze
  • 4,993
  • 2
  • 29
  • 23
  • 1
    http://wiki.fasterxml.com/JacksonInFiveMinutes#Tree_Model_Example - read and enjoy – Ashley Frieze Oct 23 '14 at 10:34
  • Thanks, still missing one piece of information. How can I use JsonNode.get/.path to interate through the object keys since I don't know their values ahead of time? – Bob Oct 23 '14 at 10:42
  • If you know what you're looking for, then you can search around a tree for it, even if you don't know the exact structure... If you have no idea what's going to be in the tree, then how can you define whether your program works? – Ashley Frieze Oct 23 '14 at 10:50
  • Nevermind answered my own question while editing the question. I'm using for (JSonNode entry: data) after doing JsonNode.get("data") to interate – Bob Oct 23 '14 at 10:59
0

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

vach
  • 10,571
  • 12
  • 68
  • 106