简体   繁体   English

将 json 转换为 flutter 中的列表

[英]Convert json to list in flutter

I have a dynamic data from json, then I want to change it to a list variable, so i can be called that variable by the getSuggestions function.我有一个来自 json 的动态数据,然后我想将它更改为一个列表变量,这样我就可以通过 getSuggestions 函数调用该变量。 Here is the code :这是代码:

static List<String> people = new List<String>();

  void getUsers() async {
    try {
      final response =
          await http.get("https://jsonplaceholder.typicode.com/users");
      var resbody = json.decode(response.body);
      var data = json.encode(resbody[0]);
      if (response.statusCode == 200) {
        setState(() {
          people = data;
        });
      } else {
        print("Error getting users.");
      }
    } catch (e) {
      print("Error getting users.");
    }
  }

  static List<String> getSuggestions(String query) {
    List<String> matches = List();
    matches.addAll(people);

    matches.retainWhere((s) => s.toLowerCase().contains(query.toLowerCase()));
    return matches;
  }```

update 1:更新1:

try it with试试看

resbody.map((entry) => (entry['name'])).toList();

old老的

could you provide more information?.你能提供更多信息吗? Fe how does the json look like? Fe json 是什么样子的? Structure etc.结构等

In most cases, json.decode already translates json arrays to flutter Lists.在大多数情况下, json.decode 已经将 json 数组转换为 flutter Lists。 Lets say your response has the following structure:假设您的响应具有以下结构:

{
  "date": "2019-07-18T06:14:36.276Z",
  "body": [
    {
      "amounts": [
        0,
        1,
        2,
      ],
      "name": "string",
    }
  ]
}

I would then suggest to create a class Data:然后我建议创建一个类数据:

class Data {
  const Data({this.date, this.body});

  factory Data.fromJson(Map<String, dynamic> parsedJson) {
    return Data(
      date: parsedJson['date'] ,
      body: Body.fromJson(parsedJson['body'],
    );
  }

  final String date;
  final Body body;
}

and a class Body和一个类身体

class Body {
  const Body({this.date, this.body});
  factory Body.fromJson(Map<String, dynamic> parsedJson) {
    return Body(
      amounts: parsedJson['amounts'],
      name: parsedJson['name'] ,
    );
  }

  final List<int> amounts;
  final String name;
}

Then data = Data.fromJson(resbody);然后data = Data.fromJson(resbody); should return the Data class.应该返回数据类。 And data.body.amounts should return the list. data.body.amounts应该返回列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM