Flutter中解析Json数据,并取出然后遍历数据。
- Json数据如下:
String jsonstr = """
{
"typeOne":[
{
"title":"单品条码",
"value":"S500036000406844116"
},{
"title":"位置",
"value":"Z10237"
},{
"title":"入库单",
"value":"W1990000000282"
}
],
"typeTwo":[
{
"one":"003274",
"two":"10",
"three":"2B",
"four":"test"
},{
"one":"CONTANT",
"two":"10",
"three":"2B"
},
{
"one":"003234",
"two":"5",
"three":"2B"
}
],
"typeThree":[
{
"index":"序号",
"barcode":"条码",
"goods":"商品",
"numbers":"数量",
"isOnShelf":"是否上架"
},{
"index":"1",
"barcode":"B04000000000000750",
"goods":"M*23398",
"numbers":"5",
"isOnShelf":"N"
},{
"index":"2",
"barcode":"B04000000000000751",
"goods":"M*23399",
"numbers":"4",
"isOnShelf":"N"
},{
"index":"3",
"barcode":"B04000000000000752",
"goods":"M*23349",
"numbers":"10",
"isOnShelf":"N"
}
]
}
""";
三个引号表示有格式的字符串。如果是Json字符串,则需要进行转化,首先要导入依赖:
import 'dart:convert';
然后将Json字符串转化为Map类型:
Map<String, dynamic> json = jsonDecode(jsonstr);
jsonDecode是json.dart里面的方法,json.dart是dart.convert的一部分。
json.forEach((key, value) {
});
上述forEach中的(key,value)就是Json数据的key和value。转化成Map时,value要是动态的,因为,value的类型不确定。上述代码解析出来的key的值有:“typeOne”, “typeTwo”, “typeThree”。而value是数组类型。上述接着解析如下:
json.forEach((key, value) {
//typeOne等所对应的数组数据
List<dynamic> list = value;
list.forEach((element){
//每个列表元素是一个Json对象,
Map<String, dynamic> content = element;
//这个content得到的是每个列表中得到的Json数据
content.forEach((k, v) {
print("k=$k,v=$v");
});
});
});
输出如下:
k=title, v=单品条码
k=value, v=S500036000406844116
......
demo地址:
flutter_html_demo