简体   繁体   English

如何使用 Gson 解析这种格式的 JSON

[英]How to parse this format of JSON using Gson

I am having Json in this format我有这种格式的 Json

{
    "Sheet1":
        [
            {
                "Title":"facebook",
                "Link":"facebook.com"
            },{
                "Title":"gmail",
                "Link":"mail.google.com"
            }
        ]
}

When I try to convert it using pojo I am getting two classes and I am not able to implement there is force close error Please Help me out.当我尝试使用 pojo 转换它时,我得到了两个类,但无法实现强制关闭错误请帮帮我。

Sheet1 is an array. Sheet1 是一个数组。

JSONArray array = (JSONArray) object.get("Sheet1");

for (int i = 0; i < array.length(); i++) {
    String title = array.getJSONObject(i).getString("Title");
    String link = array.getJSONObject(i).getString("Link");
}

This class structure will work for Gson:这个类结构适用于 Gson:

public class Response {

    private List<Sheet> Sheet1;
}

public class Sheet {

    private String Title;
    private String Link;
}

Your top-level response has one element, "Sheet1" , which is a list of items.您的顶级响应有一个元素"Sheet1" ,它是一个项目列表。 Each item in the list has two elements, "Title" and "Link" .列表中的每一项都有两个元素, "Title""Link"

Create the classes:创建类:

public class Sheet {
    String Title;
    String Link;
}

and

public class Sheets {
    Collection<Sheet> Sheet1;
}

and after deserialize with:并在反序列化后:

        public static void main(String[] args) throws Exception {
        Gson gson = new Gson();
        String filename="pathTo/sheet.json";
        JsonReader reader = new JsonReader(new FileReader(filename));
        Sheets sheet1= gson.fromJson(reader, Sheets.class);
        System.out.println(gson.toJson(sheet1));
    }

This class structure will work for Gson:这个类结构适用于 Gson:

public class Response 
{ 
  private List<Sheet> Sheet1; 
} 
public class Sheet 
{ 
  private String Title; 
  private String Link; 
}

Your top-level response has one element, "Sheet1", which is a list of items.您的顶级响应有一个元素“Sheet1”,它是一个项目列表。 Each item in the list has two elements, "Title" and "Link".列表中的每一项都有两个元素,“标题”和“链接”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM