{
{
"1234": {
"name": "bob"
}
},
{
"5678": {
"name": "dan"
}
}
}
I have a class representing name (and other fields, I've just made it simple for this question). But the each element is key'd with the id of the person.
I've tried several things including:
class Name {
String Name;
//getter and setter
}
class NameId {
String id;
Name name;
//getter and setters
}
//json is the string containing of the above json
ArrayList<NameId> map = objectMapper.readValue(json, ArrayList.class);
for (Object m : map) {
LinkedHashMap<String, NameId> l = (LinkedHashMap)m;
Map<String, NameId> value = (Map<String, NameId>) l;
//System.out.println(l);
//System.out.println(value);
for (Object key : value.keySet()) {
System.out.println("key: " + key);
System.out.println("obj: " + value.get(key));
NameId nameId = (NameId)value.get(key);
}
}
The problem I have is it doesn't allow that cast to NameId. The error I get is:
java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to NameId
Any ideas on the best way to parse such a json string like this properly?
Your json is malformed. You need the square brackets around it otherwise it isn't considered a json array. If your json looks like (for example)
[
{
"1234" : {
"name" : "dan"
}
},
{
"5678" : {
"name" : "mike"
}
}
]
you can write a custom deserializer for the object mapper. See the working example below:
public static void main(String... args) throws Exception {
String testJson = "[{ \"1234\" : { \"name\" : \"dan\" } },{ \"5678\" : { \"name\" : \"mike\" } }]";
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(NameId.class, new MyDeserializer());
mapper.registerModule(module);
ArrayList<NameId> map = mapper.readValue(testJson.getBytes(), new TypeReference<List<NameId>>() {
});
for (NameId m : map) {
System.out.println(m.id);
System.out.println(m.name.name);
System.out.println("----");
}
}
@JsonDeserialize(contentUsing = MyDeserializer.class)
static class NameId {
String id;
Name name;
//getter and setters
}
static class Name {
String name;
//getter and setter
}
static class MyDeserializer extends JsonDeserializer<NameId> {
@Override
public NameId deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException, JsonProcessingException {
JsonNode node = p.getCodec().readTree(p);
Map.Entry<String, JsonNode> nodeData = node.fields().next();
String id = nodeData.getKey();
String name = nodeData.getValue().get("name").asText();
Name nameObj = new Name();
nameObj.name = name;
NameId nameIdObj = new NameId();
nameIdObj.name = nameObj;
nameIdObj.id = id;
return nameIdObj;
}
}