2010-11-03 61 views
0

我想解析以JSON格式給出的NYT Search API的響應。 JSON字符串如下所示(節選):用Gson解析NYTimes Search API:如何反序列化嵌套的JSON元素?

{"facets" : 
    {"des_facet" : 
    [ 
     {"count" : 745 , "term" : "POLITICS AND GOVERNMENT"} , 
     {"count" : 702 , "term" : "UNITED STATES INTERNATIONAL RELATIONS"} 
    ], 
    "desk_facet" : 
    [ 
     {"count" : 2251 , "term" : "Foreign Desk"} , 
     {"count" : 242 , "term" : "Editorial Desk"} 
    ] 
    } 
} 

在Java方面,我準備了以下對象層次結構:

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; 
} 

...這顯然是行不通的。我是JSON的新手。因此,元素的嵌套結構令人困惑。

感謝您的幫助!

回答

1

定義的類結構完全匹配示例JSON,並且對我無反序列化。

// 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); 
    } 
}