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)]
,但是当我尝试对此求值时,我返回的是未定义的.
I can see that I have a list[Symbol(_original)]
when I debug, but when I try to evaluate this, I returns as undefined.
我也尝试过
-
列表列表= json.decode(有效载荷)作为列表;
-
List< dynamic>list = json.decode(payload);
-
List< dynamic>list = json.decode(payload)as List< dynamic> ;;
-
var list =(json.decode(payload)).cast< Map< String,dynamic>>>>>>();
-
var list =(json.decode(payload)).cast< Map<动态,动态>>>>();
但出现相同的错误.
{
"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屋!