如何解析对象嵌套对象的json数据格式,或者说怎么转化为json数组
1条回答 默认 最新
- 晓呆同学 2015-12-16 08:17关注
给你举个例子:
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格式的规则,一步一步来解析。先从最外层,步步深入,遇到大括弧“{}”一般就是类,遇到中括弧就考虑用数组或者列表"[]",属性也看看类型具体是啥,对应这一个一个建出来就好了。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决评论 打赏 举报无用 3
悬赏问题
- ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
- ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
- ¥15 cmd cl 0x000007b
- ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
- ¥500 火焰左右视图、视差(基于双目相机)
- ¥100 set_link_state
- ¥15 虚幻5 UE美术毛发渲染
- ¥15 CVRP 图论 物流运输优化
- ¥15 Tableau online 嵌入ppt失败
- ¥100 支付宝网页转账系统不识别账号