简体   繁体   English

如何在 Flutter 中解析这个 JSON 数组?

[英]How to parse this JSON Array in Flutter?

I am working with Flutter and am currently trying to create a graph.我正在使用 Flutter,目前正在尝试创建图表。 I am looking to parse this JSON Array from the link below.我希望从下面的链接解析这个 JSON 数组。 My issue is that the information provided in the "prices" object, the values are all inside arrays themselves.我的问题是“价格”对象中提供的信息,这些值都在数组内部。 I want to get those values and split them into an X and Y list but I have no idea how to accomplish this.我想获取这些值并将它们拆分为 X 和 Y 列表,但我不知道如何实现。 I posted a snippet of the JSON data below.我在下面发布了一段 JSON 数据。

https://api.coingecko.com/api/v3/coins/bitcoin/market_chartvs_currency=usd&days=1 https://api.coingecko.com/api/v3/coins/bitcoin/market_chartvs_currency=usd&days=1

I am only familiar with parsing data by creating a class and constructor.我只熟悉通过创建类和构造函数来解析数据。 Then create a fromJSON(Map<String, dynamic> json) class and putting the data into a list, as shown in the code snippet below that I created from another URL with object values.然后创建一个fromJSON(Map<String, dynamic> json)类并将数据放入一个列表中,如下面的代码片段所示,该代码片段是我从另一个具有对象值的 URL 创建的。 How could I go about parsing this array JSON data into two list data?我怎么能把这个数组 JSON 数据解析成两个列表数据?

CODE TO PARSE JSON解析 JSON 的代码

List<Coins> _coins = List<Coins>();
Future<List<Coins>> fetchCoins() async {
var url = 'URL';
var response = await http.get(url);

var coins = List<Coins>();

if (response.statusCode == 200) {
  var coinsJSON = json.decode(response.body);
  for (var coinJSON in coinsJSON) {
    coins.add(Coins.fromJson(coinJSON));
  }
}
return coins;
 }

@override
void initState() {
fetchCoins().then((value) {
  setState(() {
    _coins.addAll(value);
  });
});
super.initState();
}

class Coins{
String symbol;
String name;

Coins(this.symbol, this.name);

Coins.fromJson(Map<String, dynamic> json) {
symbol = json['symbol'];
name = json['name'];

JSON DATA SNIPPET JSON 数据片段

{
"prices":[
  [
     1566344769277,
     10758.856131083012
  ],
  [
     1566345110646,
     10747.91694691537
  ],
  [
     1566345345922,
     10743.789313302059
  ],
]
}

EDIT: SOLVED WITH THE HELP OF @EJABU.编辑:在@EJABU 的帮助下解决了。

class HistoricalData {
 List prices;
 List<num> listX = [];
List<num> listY = [];

HistoricalData(this.prices,this.listX, this.listY);

HistoricalData.fromJson(Map<String, dynamic> json) {
prices = json['prices'];
for (var price in prices) {
  listX.add(price[0]);
  listY.add(price[1]);
 }
}

You may try this...你可以试试这个...

New class Coins definition:新类Coins定义:

class Coins {
  List<num> listX = [];
  List<num> listY = [];

  Coins(this.listX, this.listY);

  Coins.fromJson(Map<String, dynamic> json) {
    List<List<num>> prices = json['prices'];
    for (var price in prices) {
      listX.add(price[0]);
      listY.add(price[1]);
    }
  }
}

Then later you can fetch it by these lines :然后你可以通过这些行获取它:

// Future<List<Coins>> fetchCoins() async { // Remove This
Future<Coins> fetchCoins() async {
  var url = 'URL';
  var response = await http.get(url);

  // var coins = List<Coins>(); // Remove This
  Coins coins;

  if (response.statusCode == 200) {
    var coinsJSON = json.decode(response.body);

    // Remove This
    // for (var coinJSON in coinsJSON) {
    //   coins.add(Coins.fromJson(coinJSON));
    // }
    //
    coins = Coins.fromJSON(coinsJSON);
  }
  return coins;
}

Accessing Data in Widget访问小部件中的数据

In Widgets , our expected variable resides as property inside Coins class.在 Widgets 中,我们期望的变量作为属性存在Coins类中。

For example, if you use FutureBuilder, you may use these lines:例如,如果您使用 FutureBuilder,您可以使用这些行:

child: FutureBuilder(
  future: fetchCoins(),
  builder: (_, __) {
    return SomeChartWidget(
      listX: coins.listX,
      listY: coins.listY,
    );
  },
),

Generating Serializers automatically自动生成序列化程序

I suggest you take a look at https://pub.dev/packages/json_serializable , which is a package that does the boilerplate code generation for you.我建议您查看https://pub.dev/packages/json_serializable ,这是一个为您生成样板代码的包。 Although it might me a bit overkill to add something like this to your code or your workflow, automatically generating serializers is very convenient.尽管将这样的内容添加到您的代码或工作流程中可能有点矫枉过正,但自动生成序列化程序非常方便。

Not that in order to have custom sub-classes, they need to provide serialization as well.并不是为了拥有自定义子类,它们还需要提供序列化。

If you want to extend your knowledge even further, you can also have a look at https://pub.dev/packages/built_value and https://pub.dev/packages/built_value_generator如果您想进一步扩展您的知识,您还可以查看https://pub.dev/packages/built_valuehttps://pub.dev/packages/built_value_generator

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

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