3

我正在尝试使用 Gson 将 Json 解析为 Java,但是当我使用 fromJson() 时,我总是得到 null。谁能帮我解释一下这个数据结构?谢谢!

{
"d": {
    "results": [
        {
            "__metadata": {
                "uri": "https://api.datamarket.azure.com/Data.ashx/Bing/SearchWeb/v1/Web?Query='bill'gates'&$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='bill'gates'&$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='bill'gates'&$skip=10&$top=10"
}

}

我认为数据结构应该是这样的,但它不起作用。

public class d {
  public result[] results;
  public String __next;}

public class result {
  public information[] infolist;}

public class information {
  public  __metadata metadata;
  public String ID;
  public String Title;
  public String Description;
  public String DisplayUrl;
  public String Url;}

public class __metadata {
   public String uri;
   public String type;}
4

1 回答 1

3

你的Information课是问题所在。将Information东西放入Resultinfolist从中取出Result。此外,元数据的字段名称是__metadata. 这不是类名。最后,您缺少一个要包装d为字段的类。

public class DataContainer {
    public Data d;
}

public class Data {
    public Result[] results;
    public String __next;
}

public class Result {
    public Metadata __metadata;
    public String ID;
    public String Title;
    public String Description;
    public String DisplayUrl;
    public String Url;
}

public class Metadata {
    public String uri;
    public String type;
}

您确实应该对类名使用通用约定。Gson 不会阻止您使用自己的名字来上课。它只需要控制字段的名称。

反序列化:

String json = ... ;
DataContainer myDataContainer = new Gson().fromJson(JSONString , DataContainer.class);
Result[] myResult = myDataContainer.d.results;

试试看,看看是否有效。

以下是在为 Gson 编写类结构时应如何解释 JSON:

  • 开口{表示一个对象,因此这将是一个新类(如果它们具有相同的字段,则为现有类)
  • A"this":表示它所在的对象的字段,并且该字段的名称必须与字符串中的文本相同。
  • 开口[表示数组、aList或 a Set(Result[] results也可以是List<Result> results)
于 2012-09-27T21:12:40.343 回答