解码json dart flutter

0tdrvxhp  于 2023-08-08  发布在  Flutter
关注(0)|答案(1)|浏览(126)

我需要在Dart中解码以下JSON。当我执行解码时,我遇到以下错误。我该如何解决这个问题?

**错误:**type '(Map<dynamic,dynamic>)=> RicettaNew'不是'f'类型'(dynamic)=> dynamic'的子类型
JSON:

[{"name":"ricetta1","values":
[{"key":"item1","value":"3"},
{"key":"item2","value":"8"},{"key":"item3","value":"13"}
,{"key":"item4","value":"18"},{"key":"item5","value":"23"},{"key":"item6","value":"14"},....

字符串

Flutter Code:

var serverlink = "http://207.154.221.255:8600/api/recipes"+"/"+mc.model;
      var request = http.Request('GET', Uri.parse(serverlink));
      http.StreamedResponse response = await request.send();
      if (response.statusCode == 200) {
        var result = await response.stream.bytesToString();
        print("result: "+result);
        var list = jsonDecode(result.toString());
        lista=jsonDecode(result).map((Map m)=> RicettaNew.fromJson(m)).toList();

...
class RicettaNew {
  String name;
  List<Values> values = [];

  RicettaNew(this.name, this.values);

  RicettaNew.fromJson(Map json) {
    name = json["name"];

  }
}

dgiusagp

dgiusagp1#

只需将基础[]大括号更改为{}
因为您要传递的JSON不是正确的JSON格式
JSON格式始终以{...}开始和结束

{   
    "name":"ricetta1",
    "values": [
            {"key":"item1","value":"3"},
            {"key":"item2","value":"8"},
            {"key":"item3","value":"13"},
                         {"key":"item4","value":"18"},
                         {"key":"item5","value":"23"}

            ]
}

字符串
在解码之前,解析https://jsoneditoronline.org/上的json,这样你就可以识别它的格式是否正确
https://javiercbk.github.io/json_to_dart/上生成模型类(& G)

相关问题