Parsing NYTimes Search API with Gson: How to deserialize nested JSON elements?
I would like to parse a response from the NYT Search API given in JSON format. The JSON string looks as follows (excerpt):
{"facets" :
{"des_facet" :
[
{"count" : 745 , "term" : 开发者_JAVA技巧"POLITICS AND GOVERNMENT"} ,
{"count" : 702 , "term" : "UNITED STATES INTERNATIONAL RELATIONS"}
],
"desk_facet" :
[
{"count" : 2251 , "term" : "Foreign Desk"} ,
{"count" : 242 , "term" : "Editorial Desk"}
]
}
}
On Java side, i prepared the following object hierarchy:
public class Container {
Facet facets;
}
public class Facet {
Collection<Elements> des_facet;
Collection<Elements> desk_facet;
}
public class Elements {
private int count;
private String term;
}
... which is obviously not working. I am new to JSON. Therefore, the nested structure of elements is confusing.
Thanks for your help!
The defined class structure matches the example JSON perfectly well, and deserializes without error for me.
// output:
// {Container:
// facets=
// {Facet:
// des_facet=[
// {Elements: count=745, term=POLITICS AND GOVERNMENT},
// {Elements: count=702, term=UNITED STATES INTERNATIONAL RELATIONS}
// ],
// desk_facet=[
// {Elements: count=2251, term=Foreign Desk},
// {Elements: count=242, term=Editorial Desk}
// ]
// }
// }
import java.io.FileReader;
import java.util.Collection;
import com.google.gson.Gson;
public class Foo
{
public static void main(String[] args) throws Exception
{
Gson gson = new Gson();
Container container = gson.fromJson(new FileReader("input.json"), Container.class);
System.out.println(container);
}
}
class Container
{
Facet facets;
@Override
public String toString()
{
return String.format("{Container: facets=%s}", facets);
}
}
class Facet
{
Collection<Elements> des_facet;
Collection<Elements> desk_facet;
@Override
public String toString()
{
return String.format("{Facet: des_facet=%s, desk_facet=%s}", des_facet, desk_facet);
}
}
class Elements
{
private int count;
private String term;
@Override
public String toString()
{
return String.format("{Elements: count=%d, term=%s}", count, term);
}
}
精彩评论