问题描述
我想要解析类似:{"total":100,"rows":[{"key":"key1","value":"value1"}{"key":"key2","value":"value2"}]};这种格式的数据.试用Gson该怎么实现呢? 貌似网上没看到过这样的案例... 问题补充:283433775 写道
解决方案
public class A{ public string key; public string value; }public class B { public int total; public List<A> rows;}你的jso串对应于我的对象B,请使用对象B来解析就可以了。
解决方案二:
JSON字符串错了,差个逗号,应该是 {"total":100,"rows":[{"key":"key1","value":"value1"},{"key":"key2","value":"value2"}]}private void gson1() {String json = "{"total":100,"rows":[{"key":"key1","value":"value1"},{"key":"key2","value":"value2"}]}"; Gson gson = new Gson(); B b = gson.fromJson(json, B.class); System.err.println(b.getTotal()); System.err.println("============="); System.err.println(b.getRows().size()); } public static class A { private String key=""; private String value=""; public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } } class B { private int total=0; private List<A> rows = new ArrayList<json2bean.A>(); public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public List<A> getRows() { return rows; } public void setRows(List<A> rows) { this.rows = rows; } }
解决方案三:
结构应该是283433775 说的,要定义两个类来嵌套,GSON从json转java不好使啊。。。。。不如用json-lib吧!
解决方案四:
类似如下,没有使用过GSON,下面是fastjson的使用JSON.parseObject(jsonString, beanName.class);上面的beanName是你的对应的对象名称jsonString是json字符串