我试图解析这个json
{"status":"ok","results":{"query":{"id":"6081","name":"UB1656-Palazzo Versace Resort in Culture Village","query":"Aswathy VS : <\/strong>
Test Query","add_date":"2014-08-05 08:27:45"},"replies":[{"replied_by":"Ventures Onsite","replied_on":"05-Aug-2014 09:05:19 AM","reply":"We have received your Test Query."},{"replied_by":"Me","replied_on":"05-Aug-2014 01:28:00 PM","reply":"Thanks... "}]}}
我的pojo班
import java.util.ArrayList;
public class QueryRepliesList {
public String status;
public ArrayList<Result> results;
public class Replies {
public String id;
public String name;
public String query;
public String add_date;
public String replied_by;
public String replied_on;
public String reply;
}
public class Result {
public ArrayList<Replies> query;
public ArrayList<Replies> replies;
}
}
我试着通过
QueryRepliesList queryReply = gson.fromJson(reader,
QueryRepliesList.class);
但我有个例外
原因:com.google.gson.jsonsyntaxception:java.lang.IllegalStateException:应为字符串,但为begin\u对象
我试着换衣服
根据对问题的类似回答,pojo类多次出现
但什么都没用
请大家帮忙
提前谢谢
最佳答案
基于您提供的JSON
,我看不到您将如何获得提供的错误,相反,您将看到
应为begin_数组,但为begin_对象
因为results
和query
都是JSON_OBJECT
。为了说明这一点,我把所有东西都放进了junit测试中。
@org.junit.Test
public void asPosted() {
final String json = "{'status':'ok','results':{'query':{'id':'6081','name':'UB1656-Palazzo Versace Resort in Culture Village','query':'Aswathy VS : <\\/strong>\n"
+ "Test Query','add_date':'2014-08-05 08:27:45'},'replies':[{'replied_by':'Ventures Onsite','replied_on':'05-Aug-2014 09:05:19 AM','reply':'We have received your Test Query.'},{'replied_by':'Me','replied_on':'05-Aug-2014 01:28:00 PM','reply':'Thanks... '}]}}";
QueryRepliesContainer data = new Gson().fromJson(json, QueryRepliesContainer.class);
Assert.assertEquals("ok", data.getStatus());
Assert.assertEquals(2, data.getRepliesCount());
Assert.assertEquals("6081", data.getQueryId());
}
通常,您将为每个
JSON_OBJECT
创建一个pojo。例外情况包括提供自定义反序列化程序。根据需要公开“内部”数据的程度,需要将内部类迁移到公共级公开。我将它们分别嵌套到JSON
结构中。因此,根据所提供的信息,您将需要类似于以下内容的内容: class QueryRepliesContainer {
private String status;
private Result results;
public String getStatus() {
return status;
}
public int getRepliesCount() {
return results.replies.size();
}
public String getQueryId() {
return results.query.id;
}
private class Result {
private Query query;
private List<Replies> replies;
private class Query {
private String id;
private String name;
private String query;
}
private class Replies {
private String add_date;
private String replied_by;
private String replied_on;
private String reply;
}
}
}