【问题标题】:How to get data from Json type如何从 Json 类型中获取数据
【发布时间】:2021-06-07 06:55:01
【问题描述】:

我已经尝试了很长时间从 Json Local 文件中获取数据。

此时我的代码是这样的:

static Future<String> loadJsonData() async {
    var jsonText = await rootBundle.loadString('assets/Json/CDV.json');
    data = json.decode(jsonText);
    for(int i = 0; i < data.length; i++){
      print(data[i]);
    }
    
    return 'success';
  }

我得到了:

{属性:{FID:2618,id:2619,地址:大西洋银行 - Agence Vridi, Zone Industrielle Abidjan-Ville Lagunes Côte d'Ivoire, 经度:-4.000757,纬度:5.265247},几何:{x:-4.000757,y: 5.265247}} I/flutter (26638): {attributes: {FID: 2619, id: 2620, Adresse: Prestige Auto Abidjan-Ville Lagunes Côte d'Ivoire, 经度:-4.002028,纬度:5.266179},几何:{x:-4.002028,y: 5.266179}} I/flutter (26638): {attributes: {FID: 2620, id: 2621, Adresse: banque Société générale Côte d’Ivoire Agence Vridi Abidjan-Ville Lagunes 科特迪瓦,经度:-4.004049,纬度: 5.268738},几何:{x:-4.004049,y:5.268738}} I/flutter(26638):{属性:{FID:2621,id:2622,地址:banque Bicici - Agence Vridi Abidjan-Ville Lagunes 科特迪瓦,经度:-4.013067, 纬度:5.266223},几何:{x:-4.013067,y:5.266223}} I/flutter (26638):{属性:{FID:2622,id:2623,地址:非洲银行 (BOA) - Agence Vridi Abidjan-Ville Lagunes 科特迪瓦,经度: -4.008449,纬度:5.266771},几何:{x:-4.008449,y:5.266771}}

我想从该响应中提取该地址列表,但我无法访问它;

【问题讨论】:

    标签: json flutter


    【解决方案1】:

    您需要像这样访问attributes 然后address data[i]['attributes']['Adresse']

    static Future<String> loadJsonData() async {
        var jsonText = await rootBundle.loadString('assets/Json/CDV.json');
        data = json.decode(jsonText);
        for(int i = 0; i < data.length; i++){
          print(data[i]['attributes']['Adresse']);
        }
        
        return 'success';
      }
    

    【讨论】:

      【解决方案2】:
      class Address {
        final int FID;
        final String addr;
      
        Address(this.addr, this.FID);
      
        Address.fromMap(Map m)
            : this.addr = m["Adresse"],
              this.FID = m["FID"];
      }
      
      static Future<List<Address>> loadJsonData() async {
          var jsonText = await rootBundle.loadString('assets/Json/CDV.json');
          data = json.decode(jsonText);
          var list = [];
          for(int i = 0; i < data.length; i++){
            list.add(Address.fromMap(data[i]["attributes"]);
          }
          
          return list;
        }
      
      

      【讨论】:

        【解决方案3】:

        用同样的方法查看答案here 或者您可以使用来自google 的flutter 包json_serializable 轻松获取json 数据并对其进行序列化

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-01
          • 2021-05-02
          • 2021-11-11
          • 2017-02-12
          • 2019-12-27
          • 2013-06-13
          • 2012-04-25
          • 2021-12-08
          相关资源
          最近更新 更多