Html 在 Dart 中解析 JSON 的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15866290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
The best way to parse a JSON in Dart
提问by Fernando
I'm trying to load a json file from a URL and parse it within Dart. So I had tried the following code as suggested from some links when I google for it:
我正在尝试从 URL 加载一个 json 文件并在 Dart 中解析它。所以我在谷歌搜索时按照一些链接的建议尝试了以下代码:
HttpRequest.getString("hellknight2.js").then((response)
{
var model = new JSON.parse(response);
});
However, it seems to not work anymore on Dart SDK version 0.4.3.5_r20602. What is the current best way to get a Json file mapped to an object in Dart?
但是,它似乎不再适用于 Dart SDK 版本 0.4.3.5_r20602。当前将 Json 文件映射到 Dart 中的对象的最佳方法是什么?
回答by Alexandre Ardhuin
Simply use jsonof the dart:convert
package. Here is an example :
只需使用JSON的的dart:convert
包。这是一个例子:
import 'dart:convert';
main() {
final myJsonAsString = '{"a": 1, "b": "c"}';
final decoded = json.decode(myJsonAsString);
....
}
See Parsing JSONfor more details.
有关更多详细信息,请参阅解析 JSON。
回答by Julien
in my case
就我而言
JSON.decode
JSON.decode
didn't work.
没有用。
Instead I had to use :
相反,我不得不使用:
import 'dart:convert' as JSON;
final json=JSON.jsonDecode(myJsonAsString);
回答by DaviDeMo
It depends on a lot of things.
这取决于很多事情。
Is the json text you get is an array or a map?
你得到的json文本是数组还是地图?
You can try with:
您可以尝试:
Map model = new parse(response);
Or
或者
List model = new parse(response);
but you need to import JSONObject by Chris Buckettinto your package
但是您需要将Chris Buckett 的 JSONObject导入到您的包中
import "package:json_object/json_object.dart";
You can install it from pubspec adding this dependency
您可以从 pubspec 添加此依赖项来安装它
json_object
回答by Jasper
There's a new pub package for this:
有一个新的 pub 包:
I didn't use it but seems to me that it will suite you. Try it out
我没有使用它,但在我看来它会适合你。试试看
回答by Irakli Kardava
here is my solution :) At first you need to import the convert package :
这是我的解决方案:) 首先你需要导入转换包:
import 'dart:convert';
var res = json.decode(response.body);
then you can get values by key, like below:
然后您可以通过键获取值,如下所示:
print(res["message"]);