如何将 JSON 数据转换为一个对象,以便稍后在 table 中使用它?

How to transform JSON data into an objet to use it later into a table?

我有一个 StreamBuilder 每秒给我一个 JSON。我有一个 class 调用 "fichajes",它们的属性是:id, worker_id, date, hour, type_checking_id.

JSON是:

{
  "fichajes": [
    {
      "id": 310,
      "worker_id": 1,
      "date": "30/09/2019",
      "hour": "11:07:04",
      "type_checking_id": 2,
      "zone_checking_id": null
    }
  ]
}

我想获取 json 的一个对象,以便稍后在 table 中使用它。

StreamBuilder(
      initialData: Center(
        child: new CircularProgressIndicator(),
      ),
      stream: _someData(),
      builder: (context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState != ConnectionState.done ||
            snapshot.hasError) {
          return ListView.builder(
            itemCount: 1,
            itemBuilder: (BuildContext context, int index) {
              final Fichajes fichaje = snapshot.data;
              return ListTile(
                title: Text("titulo" + fichaje.fichajes[index].id.toString()),
                subtitle: Text("subtitulo"),
              );
            },
          );
        } else {
          return Center(child: LinearProgressIndicator());
        }
      },
    );

Stream<Widget> _someData() async* {
    yield* Stream.periodic(
      Duration(seconds: 1),
      (int a) {

        //save into a general variable "allInfo" response from json
        loadUser(); 

        print("_someData");
        return getInfo();
      },
    );
  }

getInfo() {
    return new Container(
      child: new Text(allInfo.toString()),
    );
}

您可以像这样转换输出:

 Map<dynamic, dynamic> map = snapshot.data.snapshot.value;

如果你想使用 podo class 那么你应该看看里面 quicktype

您首先要使用 json helper in the dart:convert 核心库反序列化 JSON。然后,您可以访问 decodedJsonObject['fichajes'][index]['id'] 之类的数据或创建 class 以使用 .fromJson(Map<String, dynamic> json) 工厂构造函数进一步反序列化 decodedJsonObject 以将其解码为更易于使用的静态类型 class.