如何解析对象嵌套对象的json数据格式,或者说怎么转化为json数组
给你举个例子:
Json格式:
[
{
"type": "bill",
"name": "bill_id",
"label": "您查询账单如下",
"options": [
{
"label": "2013年5月",
"value": "201301011530008001140",
"amount": "13.58"
},
{
"label": "2013年6月",
"value": "201301011530008001141",
"amount": "23.47"
}
]
},
{
"type": "string",
"label": "户名",
"value": "张三"
},
{
"type": "string",
"label": "地址",
"value": "杭州市西湖区玉泉路201号"
},
{
"type": "string",
"label": "违约金(元)",
"value": "0"
},
{
"type": "string",
"label": "总应缴金额(元)",
"value": "30.23"
}
]
解析方法
建两个类:
Bill.java
package com.test;
import java.util.List;
public class Bill {
private String type;
private String name;
private String label;
private List<Option> options;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public List<Option> getOptions() {
return options;
}
public void setOptions(List<Option> options) {
this.options = options;
}
}
Option.java
package com.test;
public class Option {
private String label;
private String value;
private String amount;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
}
我们这样来解析:
package com.test;
import java.util.List;
import net.sf.json.JSONArray;
public class Test {
public static void main(String[] args) {
String jsonStr = "[{\"type\": \"bill\",\"name\": \"bill_id\",\"label\": \"您查询账单如下\",\"options\": [{\"label\": \"2013年5月\",\"value\": \"201301011530008001140\",\"amount\": \"13.58\"},{\"label\": \"2013年6月\",\"value\": \"201301011530008001141\",\"amount\": \"23.47\"}]},{\"type\": \"string\",\"label\": \"户名\",\"value\": \"张三\"},{\"type\": \"string\",\"label\": \"地址\",\"value\": \"杭州市西湖区玉泉路201号\"},{\"type\": \"string\",\"label\": \"违约金(元)\",\"value\": \"0\"},{\"type\": \"string\",\"label\": \"总应缴金额(元)\",\"value\": \"30.23\"}]";
JSONArray jsonArray = JSONArray.fromObject(jsonStr);
List<Bill> billList = (List<Bill>) JSONArray.toCollection(jsonArray, Bill.class);
System.out.println(billList.size());
}
}
另外这种解析Json格式的,大都不是很难,第一要保证Json格式正确,你可以在http://www.bejson.com/这里验证,然后你就观察Json格式的规则,一步一步来解析。先从最外层,步步深入,遇到大括弧“{}”一般就是类,遇到中括弧就考虑用数组或者列表"[]",属性也看看类型具体是啥,对应这一个一个建出来就好了。