Reputation: 2390
I'm trying to use Jackson to read JSON that looks like this:
{
api: {
version: "1.0"
},
list: [
{ // actually
foo: "foo", // x.phoo: "foo"
bar: "mane", // x.barr: "mane"
baz: "padme", // y.bazz: "padme"
qux: "hum" // y.quux: "hum"
},
...
]
}
I have the entire JSON string. All I really need is the list of objects, each of which contains the values for keys {foo bar baz quz}
. How would you go about this? I don't know whether to use JsonNode
s and navigate through the tree, or whether I can get to the list and then use ObjectMapper
to map each list item to an object.
There is an additional hitch. The keys don't actually come is as foo
bar
baz
qux
, but as x.phoo
x.barr
y.bazz
y.quux
, and I want foo
bar
baz
qux
as the field names in the objects that get created. I'm hoping to use ObjectMapper
's setPropertyNamingStrategy
method for that.
Upvotes: 0
Views: 347
Reputation: 1242
I've done something like this recently, and here's my quick-and-dirty solution.
ObjectMapper mapper = new ObjectMapper();
Map<String,Object> record = mapper.readValue( jsonString ,Map.class);
Map<String,Object>[] list = (Map<String, Object>[]) record.get("list");
/* Retrieve keyset (should be foo, bar, baz, qux) */
Set<String> keys = list[0].keySet();
/* Retrieve value of foo */
String foo = list[0].get("foo").toString();
This depends on a lot of generic object types and casting to be able to use the "list" object as an array of Maps. A more robust solution would be to an explicit class structure that mirrors the structure of your json, and pull in the json with the essentially the same code, but processing the result is simpler.
MyRecordClass record = mapper.readValue( jsonString ,MyRecordClass.class);
String foo = record.list[0].foo;
This second method depends on good mapping between your class's component variable names and your json's field names. Also on the structure matching. In general, I wouldn't bother with this unless I was going to use these record objects enough to make up for the time I've spent creating the classes.
Upvotes: 1
Reputation: 11363
You could create an object representing the whole JSON document.
@JsonIgnoreProperties(ignoreUnknown = true)
public class MyJsonDocument {
private List<Foo> foos; // just declare this one field, the rest will get ignored
...
}
and use ObjectMapper
to read the whole thing.
As for the field names,
@JsonNaming(MyXDroppingPropertyNamingStrategy.class)
public class Foo {
...
should work a charm.
Upvotes: 2