我正在编写一种flutter方法,其中我想解析一个简单的JSON数据
{"alm":3,"co2":1,"hu":2,"temp":32,"th":11,"tm":31,"ts":41}
我试图在一个简单的get类中解析它List data;
Future<String> getData() async {
http.Response response = await http.get(
Uri.encodeFull("http://chicken20.pythonanywhere.com/jsonn"),
headers: {"Accept": "application/json"});
print(response.body);
data = json.decode(response.body);
print(data);
return "Success!";
这就是我尝试在Material App中使用的方式body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new ListTile(
leading: const Icon(Icons.stay_primary_portrait),
title: Text(data.length.toString()),
subtitle:
Text('${_deviceData}'),
trailing: Icon(Icons.more_vert),
dense: true,
isThreeLine: true,
);
},
),
我得到这个错误[ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
屏幕上什么也没有显示
最佳答案
首先,来自API的响应不是json列表,而是一个简单的json对象。
如果要遍历上述对象的键,则可以创建包含所有键的列表,然后使用键索引在响应中获取实际的键名称。
final List<String> keys = ["alm","co2","hu","temp","th","tm","ts"];
那么您可以像下面那样修改您的body小部件-body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
return new ListTile(
leading: const Icon(Icons.stay_primary_portrait),
title: Text(data.length.toString()),
subtitle: Text(data[keys[index]]),
trailing: Icon(Icons.more_vert),
dense: true,
isThreeLine: true,
);
},
),
希望这可以帮助!
关于flutter - Flutter如何解析JSON数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62533880/