【问题标题】:Store Deserialized json in a list of objects Flutter将反序列化的 json 存储在对象列表中 Flutter
【发布时间】:2021-12-23 12:01:46
【问题描述】:

我已经成功反序列化了我的 json 文件。我已成功将 json 的一个元素存储在一个对象中,但在将对象存储在列表中时遇到问题。

我尝试了以下互联网上的所有可能解决方案,您将看到我所做的试验。

这是我的代码

class _MyHomePageState extends State<MyHomePage> {
  String? _chosenSubCounty;
  List<County> counties = [];

  Future<String> getJson() async {
    final jsonResult = await rootBundle.loadString('assets/json_files/counties.json');

    List<dynamic> parsedListJson = jsonDecode(jsonResult);
    print(parsedListJson[0]);//prints {name: Baringo, capital: Kabarnet, code: 30, sub_counties: [Baringo central, Baringo north, Baringo south, Eldama ravine, Mogotio, Tiaty]}

    final county = County.fromJson(parsedListJson[0]);
    print(county.name.toString());//prints Baringo

    //trial no 1 failed
    counties = parsedListJson.map((i)=>County.fromJson(i)).toList();
    //trial no 2 also failed    
    counties = List<County>.from(parsedListJson.map((i) => County.fromJson(i)));
    //trial no 3 also failed
    for(int i = 0; i < parsedListJson.length; i++){
      counties.add(County.fromJson(parsedListJson[i]));
    }

    print(counties);//prints Error: Expected a value of type 'String', but got one of type 'Null'

    return jsonResult;
  }

  @override
  void initState() {
    getJson();
  }
  @override
  Widget build(BuildContext context) {..........}

}

这是模型类

import 'dart:convert';

List<County> countyFromJson(String str) => List<County>.from(json.decode(str).map((x) => County.fromJson(x)));
String countyToJson(List<County> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class County {
  String name;
  String capital;
  int code;
  List subCounties;

  County({
    required this.name,
    required this.capital,
    required this.code,
    required this.subCounties,
  });

  factory County.fromJson(Map<String, dynamic> json) {
    
    return County(
      name: json["name"],
      capital: json["capital"],
      code: json["code"],
      subCounties: List<String>.from(json["sub_counties"])
    );
  }
  Map<String, dynamic> toJson() => {
    "name": name,
    "capital": capital == null ? null : capital,
    "code": code,
    "sub_counties": List<dynamic>.from(subCounties.map((x) => x)),
  };
  
}

这是json文件

[
    {
        "name": "Baringo",
        "capital": "Kabarnet",
        "code": 30,
        "sub_counties": [
            "Baringo central",
            "Baringo north",
            "Baringo south",
            "Eldama ravine",
            "Mogotio",
            "Tiaty"
        ]
    },
    {
        "name": "Bomet",
        "capital": "Bomet",
        "code": 36,
        "sub_counties": [
            "Bomet central",
            "Bomet east",
            "Chepalungu",
            "Konoin",
            "Sotik"
        ]
    },
]

【问题讨论】:

    标签: json flutter dart


    【解决方案1】:

    首先从 json 文件中删除第二个 json 对象后的逗号。然后使用此代码解析您的 json。我已经运行了这个项目,它工作得很好。

    import 'package:flutter/material.dart';
    import 'package:stacksolution/county_model.dart';
    
    class FetchData extends StatefulWidget {
      const FetchData({Key? key}) : super(key: key);
    
      @override
      _FetchDataState createState() => _FetchDataState();
    }
    
    class _FetchDataState extends State<FetchData> {
      @override
      void initState() {
        // TODO: implement initState
        callJson();
        super.initState();
      }
    
      callJson() async {
        String jsonString =
            await DefaultAssetBundle.of(context).loadString('assets/county.json');
        List<CountyModel> list = countyFromJson(jsonString);
        print("$list");
      }
    
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }
    

    模型类:

    import 'dart:convert';
    
    List<CountyModel> countyFromJson(String str) => List<CountyModel>.from(
        json.decode(str).map((x) => CountyModel.fromJson(x)));
    
    String countyToJson(List<CountyModel> data) =>
        json.encode(List<dynamic>.from(data.map((x) => x.toJson())));
    
    class CountyModel {
      CountyModel({
        this.name,
        this.capital,
        this.code,
        this.subCounties,
      });
    
      String? name;
      String? capital;
      int? code;
      List<String>? subCounties;
    
      factory CountyModel.fromJson(Map<String, dynamic> json) => CountyModel(
            name: json["name"],
            capital: json["capital"],
            code: json["code"],
            subCounties: List<String>.from(json["sub_counties"].map((x) => x)),
          );
    
      Map<String, dynamic> toJson() => {
            "name": name,
            "capital": capital,
            "code": code,
            "sub_counties": List<dynamic>.from(subCounties!.map((x) => x)),
          };
    }
    

    Json 文件:

    [
        {
            "name": "Baringo",
            "capital": "Kabarnet",
            "code": 30,
            "sub_counties": [
                "Baringo central",
                "Baringo north",
                "Baringo south",
                "Eldama ravine",
                "Mogotio",
                "Tiaty"
            ]
        },
        {
            "name": "Bomet",
            "capital": "Bomet",
            "code": 36,
            "sub_counties": [
                "Bomet central",
                "Bomet east",
                "Chepalungu",
                "Konoin",
                "Sotik"
            ]
        }
    ]
    

    【讨论】:

    • 我会用完整的代码更新答案
    • 这很有效,谢谢
    猜你喜欢
    • 2017-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2012-03-07
    • 2023-03-13
    • 1970-01-01
    相关资源
    最近更新 更多