如何在Flutter中解码JSON?
问题很简单,但答案并非如此,至少对我来说是这样。
我有一个使用了大量JSON字符串的项目。基本上,应用程序和服务器之间的整个通信都是通过JSON进行的。
我一直在使用JSON.decode(json_string)来处理这个问题,但今天我更新了Flutter内核(0.5.8-pre.178),JSON.decode不再可用。
我去Flutter Docs寻求帮助,但它仍然显示使用JSON.decode。
那么,从现在开始如何在Flutter中解码JSON呢?
发布于 2018-07-31 04:06:47
只需使用
json.decode()或
jsonDecode()在Dart 2中,所有尖叫大小写常量都改为小写驼峰大小写。
确保连接到import 'dart:convert';
发布于 2020-08-20 01:00:08
为了解码像这样的Json
{
"id":"xx888as88",
"timestamp":"2020-08-18 12:05:40",
"sensors":[
{
"name":"Gyroscope",
"values":[
{
"type":"X",
"value":-3.752716,
"unit":"r/s"
},
{
"type":"Y",
"value":1.369709,
"unit":"r/s"
},
{
"type":"Z",
"value":-13.085,
"unit":"r/s"
}
]
}
]
}我这样做:
void setReceivedText(String text) {
Map<String, dynamic> jsonInput = jsonDecode(text);
_receivedText = 'ID: ' + jsonInput['id'] + '\n';
_receivedText += 'Date: ' +jsonInput['timestamp']+ '\n';
_receivedText += 'Device: ' +jsonInput['sensors'][0]['name'] + '\n';
_receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][0]['type'] + '\n';
_receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][0]['value'].toString() + '\n';
_receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][1]['type'] + '\n';
_receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][1]['value'].toString() + '\n';
_receivedText += 'Type: ' +jsonInput['sensors'][0]['values'][2]['type'] + '\n';
_receivedText += 'Value: ' +jsonInput['sensors'][0]['values'][2]['value'].toString();
_historyText = '\n' + _receivedText;
}我是新手,所以,现在就为我工作吧
发布于 2021-03-14 17:44:05
您可以将JSON strings、lists和maps直接解码为对象或对象列表。
这可以通过package json_helpers实现。
import 'package:json_helpers/json_helpers.dart';
例如,只需调用一个方法,就可以将请求(request.body)的String结果直接转换为对象列表,而不会遇到太多麻烦。
详细示例:
String到Post
final text = '{"title": "Hello"}';
final post = text.json((e) => Post.fromJson(e));
print(post.title);String到List<Post>
final text = '[{"title": "Hello"}, {"title": "Goodbye"}]';
final post = text.jsonList((e) => Post.fromJson(e));
print(post[0].title);Map到Post
final map = {"title": "Hello"};
final post = map.json((e) => Post.fromJson(e));
print(post.title);List<Map>到List<Post>
final list = [{"title": "Hello"}, {"title": "Goodbye"}];
final post = list.json((e) => Post.fromJson(e));
print(post[0].title);https://stackoverflow.com/questions/51601519
复制相似问题