-1

我有这样的json数组

{
    "result": [
        {
            "nik": "1234",
            "name": "test"
        }
    ],
    "status_code": 200
}

如何从该 json 数组/对象中获取所有数据?

这是我的颤振代码

final jsonData = json.decode(response.body);
    Sample sample = Sample.fromJson(jsonData);
    setState(() {
      print(sample.result);
    });

class Sample {
  String result;
  int code;
  Sample({required this.result, required this.code});
  @override
  factory Sample.fromJson(Map<String, dynamic> json) {
    return Sample(
        result: json["result"],
        code: json["code"]
    );
  }
}

但我收到了这个错误

Error: Expected a value of type 'String', but got one of type 'List<dynamic>'
at Object.throw_ [as throw] (http://localhost:53292/dart_sdk.js:5041:11)
4

2 回答 2

0

结果是一个数组,所以你需要List保存数据。只需创建一个名为 User 的模型。

class User {
  String nik;
  String name;
  Sample({required this.nik, required this.name});
  @override
  factory User.fromJson(Map<String, dynamic> json) {
    return User(
        nik: json["nik"],
        name: json["name"]
    );
  }
}

List<User>在 Sample 类中创建一个字段。然后使用来自 User 类的 fromJson 来解析结果 json。或者使用json_serializable

于 2021-09-13T08:00:53.883 回答
0

您可以使用json_serializable 之类的包或通过使用quicktype从 json 轻松生成 dart 模型来编写容易出错的样板文件

于 2021-09-13T03:58:09.607 回答