Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 颤振列表问题中复杂json的解析_Java_Json_Flutter_Dart - Fatal编程技术网

Java 颤振列表问题中复杂json的解析

Java 颤振列表问题中复杂json的解析,java,json,flutter,dart,Java,Json,Flutter,Dart,我正在创建一个应用程序,我得到了这些json { "countries": [ { "Mainland_China": { "confirmed": 77660, "deaths": 2663, "recovered": 27650 }, "Thailand": { "confirmed": 37, "deaths": 0, "recovered

我正在创建一个应用程序,我得到了这些json

    {
  "countries": [
    {
      "Mainland_China": {
        "confirmed": 77660,
        "deaths": 2663,
        "recovered": 27650
      },
      "Thailand": {
        "confirmed": 37,
        "deaths": 0,
        "recovered": 22
} 
所以我以前做模型,给我这个


import 'dart:convert';

Corona2 corona2FromJson(str) => Corona2.fromJson(json.decode(str));



class Corona2 {
    List<Map<String, Country>> countries;
    String dt;
    double ts;

    Corona2({
        this.countries,
        this.dt,
        this.ts,
    });

    factory Corona2.fromJson(Map<String, dynamic> json) => Corona2(
        countries: List<Map<String, Country>>.from(json["countries"].map((x) => Map.from(x).map((k, v) => MapEntry<String, Country>(k, Country.fromJson(v))))),
        dt: json["dt"],
        ts: json["ts"],
    );

}

class Country {
    int confirmed;
    int deaths;
    int recovered;

    Country({
        this.confirmed,
        this.deaths,
        this.recovered,
    });

    factory Country.fromJson(Map<String, dynamic> json) => Country(
        confirmed: json["confirmed"],
        deaths: json["deaths"],
        recovered: json["recovered"],
    );

    Map<String, dynamic> toJson() => {
        "confirmed": confirmed,
        "deaths": deaths,
        "recovered": recovered,
    };
}

导入“dart:convert”;
Corona2 corona2FromJson(str)=>Corona2.fromJson(json.decode(str));
第2类{
列出国家名单;
字符串dt;
双T;
冠2({
这个国家,
这个,这个,,
这个是,
});
工厂Corona2.fromJson(映射json)=>Corona2(
国家:List.from(json[“countries”].map((x)=>map.from(x).map((k,v)=>MapEntry(k,Country.fromJson(v‘)’)),
dt:json[“dt”],
ts:json[“ts”],
);
}
阶级国家{
int确认;
死亡人数;
int恢复;
国家({
这个,证实,,
这就是死亡,
这个,恢复了,,
});
工厂国家。fromJson(映射json)=>国家(
已确认:json[“已确认”],
死亡:json[“死亡”],
已恢复:json[“已恢复”],
);
映射到JSON()=>{
“已确认”:已确认,
“死亡”:死亡,
“已恢复”:已恢复,
};
}
但当我在未来称之为


  Future<Corona2> cargarPaises() async {
    final response =
        await http.get('https://covid2019-api.herokuapp.com/current_list');

        return corona2FromJson(response.body);


Future cargarPaises()异步{
最后答复=
等待http.get('https://covid2019-api.herokuapp.com/current_list');
返回corona2FromJson(response.body);
我犯了一个错误,说

type 'Corona2' is not a subtype of type 'List<Corona2>'
类型“Corona2”不是类型“List”的子类型

我尝试了所有的方法尝试在模型中列出一个列表我不知道如何解决这个问题我有一周的时间来解决这个问题

我解决了一些问题,还添加了类型,你可以自己调试。 在您的实现中,您有多个问题,但主要是尝试将
Map
用作
List
。 我还建议改进json文件,并将
国家移动到层次结构的上层。之后,您可以在
映射['Countries'][0]
中删除
[0]
。 但它肯定是可解析的json,下面的示例说明了这一点

import 'dart:convert';

import 'package:http/http.dart' as http;

Future<Corona2> testMethod() async {
  final response = await http.get('https://covid2019-api.herokuapp.com/current_list');

  return Corona2.fromJson(json.decode(response.body) as Map<String, dynamic>);
}

class Corona2 {
  Corona2({this.countries, this.dt, this.ts});
  Corona2.fromJson(Map<String, dynamic> map) {
    if (map['countries'] != null) {
      countries = <Country>[];
      final remoteCountries = map['countries'][0] as Map;
      remoteCountries.forEach((v, e) {
        countries.add(Country.fromJson(e as Map<String, dynamic>));
      });
    }
    dt = map['dt'] as String;
    ts = map['ts'] as double;
  }

  List<Country> countries;
  String dt;
  double ts;

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    if (countries != null) {
      data['countries'] = countries.map((v) => v.toJson()).toList();
    }
    data['dt'] = dt;
    data['ts'] = ts;
    return data;
  }
}

class Country {
  Country({
    this.confirmed,
    this.deaths,
    this.recovered,
  });

  factory Country.fromJson(Map<String, dynamic> json) => Country(
        confirmed: json["confirmed"] as int,
        deaths: json["deaths"] as int,
        recovered: json["recovered"] as int,
      );

  int confirmed;
  int deaths;
  int recovered;

  Map<String, dynamic> toJson() => {
        "confirmed": confirmed,
        "deaths": deaths,
        "recovered": recovered,
      };
}
导入'dart:convert';
将“package:http/http.dart”导入为http;
Future testMethod()异步{
最终响应=等待http.get('https://covid2019-api.herokuapp.com/current_list');
返回Corona2.fromJson(json.decode(response.body)作为映射);
}
第2类{
Corona2({this.countries,this.dt,this.ts});
Corona2.fromJson(映射){
if(映射['countries'!=null){
国家=[];
最终remoteCountries=地图['countries'][0]作为地图;
偏远国家。forEach((v,e){
countries.add(Country.fromJson(e作为地图));
});
}
dt=映射['dt']作为字符串;
ts=映射['ts']为双精度;
}
列出国家名单;
字符串dt;
双T;
映射到JSON(){
最终地图数据={};
如果(国家!=null){
数据['countries']=countries.map((v)=>v.toJson()).toList();
}
数据['dt']=dt;
数据['ts']=ts;
返回数据;
}
}
阶级国家{
国家({
这个,证实,,
这就是死亡,
这个,恢复了,,
});
工厂国家。fromJson(映射json)=>国家(
已确认:json[“已确认”]为int,
死亡:json[“死亡”]作为int,
已恢复:json[“已恢复”]为int,
);
int确认;
死亡人数;
int恢复;
映射到JSON()=>{
“已确认”:已确认,
“死亡”:死亡,
“已恢复”:已恢复,
};
}
调用testMethod以获取Corona2结果

也许我从您的代码中看到的是当您调用方法cargarPaises()时,因为您已经发出了get请求,并且根据您从QuickType.io创建的模型类。但是当您将响应传递给此

final corona2 = corona2FromJson(response.body);
因此,您得到的是单个Corona2对象,而不是列表[Corona2]

我有点困惑,你想实现什么,你想在列表中解析列表中的国家吗

因此,后来我正在进行这项工作,我已使其工作,只需检查以下代码:

下面是我在本地获取并解析的json:

{
    "countries": [{
        "Mainland_China": {
            "confirmed": 78065,
            "deaths": 2715,
            "recovered": 30053
        },
        "Thailand": {
            "confirmed": 40,
            "deaths": 0,
            "recovered": 22
        },
        "Japan": {
            "confirmed": 189,
            "deaths": 2,
            "recovered": 22
        },
        "South_Korea": {
            "confirmed": 1261,
            "deaths": 12,
            "recovered": 22
        },
        "Taiwan": {
            "confirmed": 32,
            "deaths": 1,
            "recovered": 5
        },
        "US": {
            "confirmed": 59,
            "deaths": 0,
            "recovered": 6
        },
        "Macau": {
            "confirmed": 10,
            "deaths": 0,
            "recovered": 7
        },
        "Hong_Kong": {
            "confirmed": 91,
            "deaths": 2,
            "recovered": 24
        },
        "Singapore": {
            "confirmed": 93,
            "deaths": 0,
            "recovered": 62
        },
        "Vietnam": {
            "confirmed": 16,
            "deaths": 0,
            "recovered": 16
        },
        "France": {
            "confirmed": 18,
            "deaths": 2,
            "recovered": 11
        },
        "Nepal": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 1
        },
        "Malaysia": {
            "confirmed": 22,
            "deaths": 0,
            "recovered": 18
        },
        "Canada": {
            "confirmed": 11,
            "deaths": 0,
            "recovered": 3
        },
        "Australia": {
            "confirmed": 22,
            "deaths": 0,
            "recovered": 11
        },
        "Cambodia": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 1
        },
        "Sri_Lanka": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 1
        },
        "Germany": {
            "confirmed": 27,
            "deaths": 0,
            "recovered": 15
        },
        "Finland": {
            "confirmed": 2,
            "deaths": 0,
            "recovered": 1
        },
        "United_Arab_Emirates": {
            "confirmed": 13,
            "deaths": 0,
            "recovered": 4
        },
        "Philippines": {
            "confirmed": 3,
            "deaths": 1,
            "recovered": 1
        },
        "India": {
            "confirmed": 3,
            "deaths": 0,
            "recovered": 3
        },
        "Italy": {
            "confirmed": 453,
            "deaths": 12,
            "recovered": 3
        },
        "UK": {
            "confirmed": 13,
            "deaths": 0,
            "recovered": 8
        },
        "Russia": {
            "confirmed": 2,
            "deaths": 0,
            "recovered": 2
        },
        "Sweden": {
            "confirmed": 2,
            "deaths": 0,
            "recovered": 0
        },
        "Spain": {
            "confirmed": 13,
            "deaths": 0,
            "recovered": 2
        },
        "Belgium": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 1
        },
        "Others": {
            "confirmed": 705,
            "deaths": 4,
            "recovered": 10
        },
        "Egypt": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Iran": {
            "confirmed": 139,
            "deaths": 19,
            "recovered": 49
        },
        "Lebanon": {
            "confirmed": 2,
            "deaths": 0,
            "recovered": 0
        },
        "Iraq": {
            "confirmed": 5,
            "deaths": 0,
            "recovered": 0
        },
        "Oman": {
            "confirmed": 4,
            "deaths": 0,
            "recovered": 0
        },
        "Afghanistan": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Bahrain": {
            "confirmed": 33,
            "deaths": 0,
            "recovered": 0
        },
        "Kuwait": {
            "confirmed": 26,
            "deaths": 0,
            "recovered": 0
        },
        "Algeria": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Croatia": {
            "confirmed": 3,
            "deaths": 0,
            "recovered": 0
        },
        "Switzerland": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Austria": {
            "confirmed": 2,
            "deaths": 0,
            "recovered": 0
        },
        "Israel": {
            "confirmed": 2,
            "deaths": 0,
            "recovered": 0
        },
        "Pakistan": {
            "confirmed": 2,
            "deaths": 0,
            "recovered": 0
        },
        "Brazil": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Georgia": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Greece": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "North_Macedonia": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Norway": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        },
        "Romania": {
            "confirmed": 1,
            "deaths": 0,
            "recovered": 0
        }
    }],
    "dt": "2/26/20",
    "ts": 1582675200.0
}
为json定义的模型类:

// To parse this JSON data, do
//
//     final corona2 = corona2FromJson(jsonString);

import 'dart:convert';

Corona2 corona2FromJson(String str) => Corona2.fromJson(json.decode(str));

String corona2ToJson(Corona2 data) => json.encode(data.toJson());

class Corona2 {
    List<Map<String, Country>> countries;
    String dt;
    double ts;

    Corona2({
        this.countries,
        this.dt,
        this.ts,
    });

    factory Corona2.fromJson(Map<String, dynamic> json) => Corona2(
        countries: List<Map<String, Country>>.from(json["countries"].map((x) => Map.from(x).map((k, v) => MapEntry<String, Country>(k, Country.fromJson(v))))),
        dt: json["dt"],
        ts: json["ts"],
    );

    Map<String, dynamic> toJson() => {
        "countries": List<dynamic>.from(countries.map((x) => Map.from(x).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())))),
        "dt": dt,
        "ts": ts,
    };
}

class Country {
    int confirmed;
    int deaths;
    int recovered;

    Country({
        this.confirmed,
        this.deaths,
        this.recovered,
    });

    factory Country.fromJson(Map<String, dynamic> json) => Country(
        confirmed: json["confirmed"],
        deaths: json["deaths"],
        recovered: json["recovered"],
    );

    Map<String, dynamic> toJson() => {
        "confirmed": confirmed,
        "deaths": deaths,
        "recovered": recovered,
    };
}

//要解析此JSON数据,请执行以下操作
//
//最终corona2=corona2FromJson(jsonString);
导入“dart:convert”;
Corona2 corona2FromJson(String str)=>Corona2.fromJson(json.decode(str));
字符串corona2ToJson(Corona2数据)=>json.encode(data.toJson());
第2类{
列出国家名单;
字符串dt;
双T;
冠2({
这个国家,
这个,这个,,
这个是,
});
工厂Corona2.fromJson(映射json)=>Corona2(
国家:List.from(json[“countries”].map((x)=>map.from(x).map((k,v)=>MapEntry(k,Country.fromJson(v‘)’)),
dt:json[“dt”],
ts:json[“ts”],
);
映射到JSON()=>{
“国家”:List.from(countries.map((x)=>map.from(x).map((k,v)=>MapEntry(k,v.toJson())),
“dt”:dt,
“ts”:ts,
};
}
阶级国家{
int确认;
死亡人数;
int恢复;
国家({
这个,证实,,
这就是死亡,
这个,恢复了,,
});
工厂国家。fromJson(映射json)=>国家(
已确认:json[“已确认”],
死亡:json[“死亡”],
已恢复:json[“已恢复”],
);
映射到JSON()=>{
“已确认”:已确认,
“死亡”:死亡,
“已恢复”:已恢复,
};
}
以及ui与数据交互的主文件:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'dummy.dart';

main() => runApp(MyApp());

class Countries {
  String name;
  String confirmed;
  String deaths;
  String recovered;

  Countries(this.name, this.confirmed, this.deaths, this.recovered);
}

class MyApp extends StatefulWidget {
  @override
  _UploadImageState createState() => _UploadImageState();
}

class _UploadImageState extends State<MyApp> {
  bool _isLoading = false;
  List<Object> objectList = List();
  List<Countries> countries = List();

  Future<String> loadFromAssets() async {
    return await rootBundle.loadString('json/parse.json');
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadYourData();
  }

  loadYourData() async {
    setState(() {
      _isLoading = true;
    });

    String jsonString = await loadFromAssets();
    final corona2 = corona2FromJson(jsonString);

    for (int i = 0; i < corona2.countries.length; i++) {
      corona2.countries[i].forEach((key, value) {
        print(value.confirmed.toString());

        countries.add(Countries(key, value.confirmed.toString(),
            value.deaths.toString(), value.recovered.toString()));
      });
    }
    print('This is the coutries data ${countries.length}');

    setState(() {
      _isLoading = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    String selectedFruit;

    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Container(
            child: new ListView.builder(
                itemCount: countries.length,
                itemBuilder: (BuildContext ctxt, int index) {
                  return Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Card(
                                        child: Padding(
                                          padding: const EdgeInsets.all(8.0),
                                          child: Column(
                        children: <Widget>[
                          Row(
                            children: <Widget>[
                              Text('Coutrt name :'),
                              Text(countries[index].name)
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Text(' Confirmed :'),
                              Text(countries[index].confirmed)
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Text(' Death:'),
                              Text(countries[index].deaths)
                            ],
                          ),
                          Row(
                            children: <Widget>[
                              Text('Recovered:'),
                              Text(countries[index].recovered)
                            ],
                          ),
                        ],
                      ),
                                        ),
                    ),
                  );
                })),
      ),
    );
  }
}

导入“包装:颤振/材料.省道”;
导入“包:flifter/services.dart”;
导入“dummy.dart”;
main()=>runApp(MyApp());
阶级国家{
字符串名;
字符串已确认;
连续死亡;
回收管柱;
国家(this.name,this.confirmed,this.death,this.recovered);
}
类MyApp扩展了StatefulWidget{
@凌驾
_UploadImageState createState()=>_UploadImageState();
}
类_UploadImageState扩展状态{
bool_isLoading=false;
List objectList=List();
列表国家=列表();
Future loadFromAssets()异步{
返回wait-rootBundle.loadString('json/parse.json');
}
@凌驾
void initState(){
//TODO:实现initState
super.initState();
装载你的