2012-09-27 66 views
1

我正在使用Bing Search API来获取Web结果。我得到了前两个文档,JSON如下所示。我该如何解析json到java

{"d": 
{"results": 
[{"__metadata": 
    {"uri":"https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Web?Query=\u0027bill\u0027gates\u0027&$skip=0&$top=1","type":"WebResult"}, 
    "ID":"9bd0942f-fe5b-44fc-8343-ef85e5b93a7e", 
    "Title":"The Official Site of Bill Gates - The Gates Notes", 
    "Description":"In the space between business and goverment, even a small investment can make a big impact on the lives of those in need.", 
    "DisplayUrl":"www.thegatesnotes.com", 
    "Url":"http://www.thegatesnotes.com/"}, 

{"__metadata": 
    {"uri":"https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Web?Query=\u0027bill\u0027gates\u0027&$skip=1&$top=1","type":"WebResult"}, 
    "ID":"fdf0d3b9-b29f-43ef-b5ba-6bb4b1b04458", 
    "Title":"Bill Gates - Wikipedia, the free encyclopedia", 
    "Description":"William Henry \"Bill\" Gates III (born October 28, 1955) is an American business magnate and philanthropist. Gates is the former chief executive and current chairman of ...", 
    "DisplayUrl":"en.wikipedia.org/wiki/Bill_Gates", 
    "Url":"http://en.wikipedia.org/wiki/Bill_Gates"}, 

], 
"__next":"https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Web?Query=\u0027bill\u0027gates\u0027&$skip=10&$top=10" 
} 
} 

我该如何使用Gson将其解析为Java?

+4

在http://code.google.com/阅读文档p/google-gson/ – Jesper

+1

这很简单。展示你的努力,我会很乐意提供帮助。 – Nishant

+0

我建立了两个类d和元数据,但是当我使用fromJson()时,我得到了null。我只是不知道这个Json字符串的数据结构。 –

回答

1
public class Metadata{ 
    public String uri; 
    public String Query; 
    public String ID; 
    public String Title; 
    public String Description; 
    public String DisplayUrl; 
    public String Url; 
} 

public class ResponseResults{ 
    public MetadataContainer[] results; 
    public String __next; 
} 


public class MetadataContainer{ 
    public Metadata __metadata; 
} 


public class ResponseData{ 
    public ResponseResults d; 
} 

String json; //Your json response 
ResponseData myD = new Gson().fromJson(json, ResponseData.class); 
+0

嗨,我用你的数据结构,但myD为空。这个结构有什么问题吗? –

+0

是的。没有测试它。我会编辑答案 – Greensy

+0

是的,在“d”之外有一个容器!谢谢! –

2
import java.io.BufferedReader; 
import java.io.FileReader; 
import java.io.IOException; 
import com.google.gson.Gson; 

public class GsonDemo { 
    public static void main(String[] args) { 
    Gson gson = new Gson(); 
    try { 
     String json = "" ; // your json string 
     //convert the json string to object 
     YourObject obj = gson.fromJson(json, YourObject.class); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 
}