Reputation: 1924
I'm trying to deserialize JSON Object coming from an application I can't control. Here my JSON :
{"assembly":
{"name":"mm9",
"id":32,
"chromosomes":[
{"chromosome":
{"name":"MT"}
}]}}
My Pojos, are
class Assembly{
private String name;
private int id;
private ArrayList<Chromosome> chromosomes;
// getters & setters
}
class Chromosome {
private String name;
//getter/setters
}
But it's not working because of the extra fields "assembly" & "chromosome", so with a JSON like :
{"name":"mm9",
"id":32,
"chromosomes":[
{"name":"MT"}
] }}
it simply working. Is there a way to modify configuration or something to achieve this without create more complex POJOS?
Upvotes: 2
Views: 1626
Reputation: 140041
The problem is that in the first JSON snippet, chromosomes
is a dictionary (Map), of which one of the entries (chromosome
) happens to correspond to your Chromosome
object.
A more accurate direct mapping to a Java class would be
class Assembly{
...
private Map<String, Chromosome> chromosomes;
}
Since you mention you can't control the format of the source JSON, you may want to look into using custom deserializers, or perhaps using the streaming support from Jackson rather than ObjectMapper for direct mapping, if you aren't happy changing your POJOs in this way.
By the way, it is best to refer to collections by their interface type (List
) rather than a concrete type (ArrayList
). It is very unlikely that code that refers to this class truly cares or needs to know that it is using an ArrayList
, referring to just the List
interface instead makes it a lot easier to swap other implementations in if needed (as a general principle).
Upvotes: 1