Dart 2 和解析 json [英] Dart 2 and parsing json
问题描述
我正在尝试使用 Dart 2 for web 将 json 解析为产品列表.
Im trying to parse json into a list of Products using Dart 2 for web.
我有以下课程:
class Product {
final String Problem;
final String Owner;
final String Description;
const Product({
this.Problem,
this.Owner,
this.Description,
});
factory Product.parse(Map<String, dynamic> json) {
print(json);
return new Product(
Problem: json["Problem"],
Owner: json["Owner"],
Description: json["Description"]
);
}
}
我正在尝试使用以下方法解析它:
And I am trying to parse this using:
Stream<Product> getProducts() async* {
final payload = await HttpRequest.getString("products.json");
print(payload);
//var _json = (json.decode(payload));
print("break");
var list = json.decode(payload);
print(list);
//print(list);
final productList = (json.decode(payload) as List).cast<Map<String, dynamic>>();
}
但是这失败并出现此错误:
However this fails with this error:
例外:类型_JsonMap"不是预期类型的子类型'列表'.
EXCEPTION: Type '_JsonMap' is not a subtype of expected type 'List'.
我可以看到我在调试时有一个 list[Symbol(_original)]
,但是当我尝试评估它时,我返回为 undefined.
I can see that I have a list[Symbol(_original)]
when I debug, but when I try to evaluate this, I returns as undefined.
我也试过
List list = json.decode(payload) as List;
列表<动态>list = json.decode(payload);
列表<动态>list = json.decode(payload) as List
; var list = (json.decode(payload)).cast
var list = (json.decode(payload)).cast
但得到同样的错误.
{
"Product_One": {
"Owner": "test",
"Description": "test description",
"Theme_Objective": "test objective",
"Technical_details": "test technical details",
"Problem": "test",
"Solution": "test"
}
}
推荐答案
你的 JSON 不包含任何列表,都是地图.当您尝试将 Map
转换为 List
时,它必须失败,因为映射不是列表.
Your JSON does not contain any list, it's all maps.
When you try to cast a Map
to List
, it has to fail since maps are not lists.
也许你想做:
final productList = (jsonDecode(payload) as Map).values.toList();
这会为您提供一个产品地图列表,其中没有您似乎不会使用的名称.
This gives you a list of the product maps, without the names that you don't appear to be using anyway.
这篇关于Dart 2 和解析 json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!