首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >未处理的异常: NoSuchMethodError:在null (json分析)上调用了方法'[]‘

未处理的异常: NoSuchMethodError:在null (json分析)上调用了方法'[]‘
EN

Stack Overflow用户
提问于 2020-03-31 12:12:19
回答 1查看 866关注 0票数 1

我正在尝试解析这个输出'confirmed‘的json。

代码语言:javascript
运行
AI代码解释
复制
{
  "Delhi": {
    "districtData": {
      "East Delhi": {
        "confirmed": 1,
        "lastupdatedtime": ""
      },
      "South West Delhi": {
        "confirmed": 3,
        "lastupdatedtime": ""
      },
      "West Delhi": {
        "confirmed": 2,
        "lastupdatedtime": ""
      },
      "North Delhi": {
        "confirmed": 3,
        "lastupdatedtime": ""
      },
      "New Delhi": {
        "confirmed": 3,
        "lastupdatedtime": ""
      },
      "South Delhi": {
        "confirmed": 2,
        "lastupdatedtime": ""
      },
      "North East Delhi": {
        "confirmed": 1,
        "lastupdatedtime": ""
      },
      "North West Delhi": {
        "confirmed": 3,
        "lastupdatedtime": ""
      },
      "Unknown": {
        "confirmed": 53,
        "lastupdatedtime": ""
      },
      "Delhi": {
        "confirmed": 1,
        "lastupdatedtime": ""
      }
    }
  }
}

https://api.covid19india.org/state_district_wise.json是实际的json数据,并且只反序列化了data数据,因为我想测试它是对还是错。它是as

代码语言:javascript
运行
AI代码解释
复制
class IndiaState {
  Delhi delhi;

  IndiaState({
    this.delhi,
  });

  factory IndiaState.fromJson(Map<String, dynamic> json) => IndiaState(
    delhi: Delhi.fromJson(json["Delhi"]),
  );
}

class Delhi {
  DelhiDistrictData districtData;

  Delhi({
    this.districtData,
  });

  factory Delhi.fromJson(Map<String, dynamic> json) => Delhi(
    districtData: DelhiDistrictData.fromJson(json["districtData"]),
  );
}

class DelhiDistrictData {
  DelhiValue eastDelhi;
  DelhiValue southWestDelhi;
  DelhiValue westDelhi;
  DelhiValue delhi;
  DelhiValue southDelhi;
  DelhiValue northEastDelhi;
  DelhiValue northDelhi;
  DelhiValue northWestDelhi;
  DelhiValue unknown;
  DelhiValue newDelhi;

  DelhiDistrictData({
    this.eastDelhi,
    this.southWestDelhi,
    this.westDelhi,
    this.delhi,
    this.southDelhi,
    this.northEastDelhi,
    this.northDelhi,
    this.northWestDelhi,
    this.unknown,
    this.newDelhi,
  });

  factory DelhiDistrictData.fromJson(Map<String, dynamic> json) => DelhiDistrictData(
    eastDelhi: DelhiValue.fromJson(json["East Delhi"]),
    southWestDelhi: DelhiValue.fromJson(json["South West Delhi"]),
    westDelhi: DelhiValue.fromJson(json["West Delhi"]),
    delhi: DelhiValue.fromJson(json["Delhi"]),
    southDelhi: DelhiValue.fromJson(json["South Delhi"]),
    northEastDelhi: DelhiValue.fromJson(json["North East Delhi"]),
    northDelhi: DelhiValue.fromJson(json["North Delhi"]),
    northWestDelhi: DelhiValue.fromJson(json["North West Delhi"]),
    newDelhi: DelhiValue.fromJson(json["New Delhi"]),
    unknown: DelhiValue.fromJson(json["Unknown"]),
  );
}

class DelhiValue {
  int confirmed;
  String lastupdatedtime;


  DelhiValue({
    this.confirmed,
    this.lastupdatedtime,
  });

  factory DelhiValue.fromJson(Map<String, dynamic> json) => DelhiValue(
    confirmed: json['confirmed'],
    lastupdatedtime: json["lastupdatedtime"],
  );
}

现在我正在尝试将确认的结果打印为德里的任何一个区

代码语言:javascript
运行
AI代码解释
复制
  @override
  void initState() {
    // TODO: implement initState
    setState(() {
      isLoading = true;
    });

    givenFunction();

    setState(() {
      isLoading = false;
    });
  }

  Future givenFunction() async {
    final httpRequest = await http.get(districtAPI);
    final json = jsonDecode(httpRequest.body);
    IndiaState firstObject = new IndiaState.fromJson(json);
    print(firstObject.delhi.districtData.eastDelhi.confirmed.toString());
  }

现在,当我尝试打印eastDelhi确认数据时,出现了错误

代码语言:javascript
运行
AI代码解释
复制
E/flutter ( 5895): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method '[]' was called on null.
E/flutter ( 5895): Receiver: null
E/flutter ( 5895): Tried calling: []("confirmed")
E/flutter ( 5895): #0      Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter ( 5895): #1      new DelhiValue.fromJson (package:coraona2903/models/district_state.dart:77:20)
E/flutter ( 5895): #2      new DelhiDistrictData.fromJson (package:coraona2903/models/district_state.dart:54:23)
E/flutter ( 5895): #3      new Delhi.fromJson (package:coraona2903/models/district_state.dart:21:37)
E/flutter ( 5895): #4      new IndiaState.fromJson (package:coraona2903/models/district_state.dart:9:18)
E/flutter ( 5895): #5      Covid19ScreenState.givenFunction (package:coraona2903/screens/covid_19_screen.dart:37:34)
E/flutter ( 5895): <asynchronous suspension>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-31 13:25:17

只需检查修改后的代码:

以下是您提供的本地json:

代码语言:javascript
运行
AI代码解释
复制
{
    "Delhi": {
      "districtData": {
        "East Delhi": {
          "confirmed": 1,
          "lastupdatedtime": ""
        },
        "South West Delhi": {
          "confirmed": 3,
          "lastupdatedtime": ""
        },
        "West Delhi": {
          "confirmed": 2,
          "lastupdatedtime": ""
        },
        "North Delhi": {
          "confirmed": 3,
          "lastupdatedtime": ""
        },
        "New Delhi": {
          "confirmed": 3,
          "lastupdatedtime": ""
        },
        "South Delhi": {
          "confirmed": 2,
          "lastupdatedtime": ""
        },
        "North East Delhi": {
          "confirmed": 1,
          "lastupdatedtime": ""
        },
        "North West Delhi": {
          "confirmed": 3,
          "lastupdatedtime": ""
        },
        "Unknown": {
          "confirmed": 53,
          "lastupdatedtime": ""
        },
        "Delhi": {
          "confirmed": 1,
          "lastupdatedtime": ""
        }
      }
    }
  }

稍后,我为此创建了一个模型类:

代码语言:javascript
运行
AI代码解释
复制
// To parse this JSON data, do
//
//     final indiaState = indiaStateFromJson(jsonString);

import 'dart:convert';

IndiaState indiaStateFromJson(String str) => IndiaState.fromJson(json.decode(str));

String indiaStateToJson(IndiaState data) => json.encode(data.toJson());

class IndiaState {
    Delhi delhi;

    IndiaState({
        this.delhi,
    });

    factory IndiaState.fromJson(Map<String, dynamic> json) => IndiaState(
        delhi: Delhi.fromJson(json["Delhi"]),
    );

    Map<String, dynamic> toJson() => {
        "Delhi": delhi.toJson(),
    };
}

class Delhi {
    Map<String, DistrictDatum> districtData;

    Delhi({
        this.districtData,
    });

    factory Delhi.fromJson(Map<String, dynamic> json) => Delhi(
        districtData: Map.from(json["districtData"]).map((k, v) => MapEntry<String, DistrictDatum>(k, DistrictDatum.fromJson(v))),
    );

    Map<String, dynamic> toJson() => {
        "districtData": Map.from(districtData).map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
    };
}

class DistrictDatum {
    int confirmed;
    String lastupdatedtime;

    DistrictDatum({
        this.confirmed,
        this.lastupdatedtime,
    });

    factory DistrictDatum.fromJson(Map<String, dynamic> json) => DistrictDatum(
        confirmed: json["confirmed"],
        lastupdatedtime: json["lastupdatedtime"],
    );

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

下面是我在列表视图中显示的主文件,请查看它:

代码语言:javascript
运行
AI代码解释
复制
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:sample_project_for_api/model.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  bool isLoading = false;
  List<Cities> citilesList = List();

  // here i have taken the  json locally which you posted on stack 
  Future<String> loadFromAssets() async {
    return await rootBundle.loadString('json/parse.json');
  }

  @override
  void initState() {
    super.initState();
    givenFunction();
  }

  Future givenFunction() async {
    setState(() {
      isLoading = true;
    });

    //final httpRequest = await http.get(districtAPI);
    //final json = jsonDecode(httpRequest.body);
    // you can make the http call above just uncomment is and comment the below line
    String jsonString = await loadFromAssets();
    // Here you can just replace down your httpRequest.body with jsonString
    final indiaState = indiaStateFromJson(jsonString);
    indiaState.delhi.districtData.forEach((key, value) {
      // This column is show you the values are getting fetched and printed below
      print('This is the key : ' + key);
      print('Confirmed :' + value.confirmed.toString());
      citilesList.add(Cities(key, value.confirmed));
    });
    setState(() {
      isLoading = false;
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: isLoading
            ? CircularProgressIndicator()
            : ListView.builder(
                itemCount: citilesList.length,
                itemBuilder: (BuildContext context, int index) {
                  return Container(
                    child: Card(
                      margin:
                          EdgeInsets.symmetric(vertical: 10, horizontal: 10),
                      child: Padding(
                        padding: const EdgeInsets.all(15.0),
                        child: Row(
                          children: <Widget>[
                            Text(citilesList[index].state + ": "),
                            Text(citilesList[index].confirmed.toString())
                          ],
                        ),
                      ),
                    ),
                  );
                },
              ),
      ),
    );
  }
}

void main() {
  runApp(HomePage());
}

class Cities {
  final String state;
  final int confirmed;

  Cities(this.state, this.confirmed);
}

刚刚为数据获取项添加了一个示例图像:

如果有效,请让我知道

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60950296

复制
相关文章
Microsoft/thrifty:RPC方法返回NULL的异常处理
版权声明:本文为博主原创文章,转载请注明源地址。 https://blog.csdn.net/10km/article/details/86244875
10km
2019/05/25
1.5K0
.net捕捉全局未处理异常的3种方式
 我们在实际项目开发中,经常会遇到一些不可预见的异常产生,有的异常在程序运行时就对其进行处理(try) 但是,有的程序不需要每一个地方都用try进行处理,那么针对这种情况,可以参照下面的方式,实现对异常的统一抓取处理
小小许
2018/09/20
1.4K0
[PHP]json_encode中文JSON_UNESCAPED_UNICODE在php5.3返回null
注意当json_encode中文的时候 , 默认是以unicode编码的 , 如果想变成中文需要增加参数JSON_UNESCAPED_UNICODE
唯一Chat
2021/02/04
7580
在 Kubernetes 上调度 GPU 资源
Kubernetes 实现了 Device Plugins[1] 以允许 Pod 访问类似 GPU 这类特殊的硬件功能特性。作为运维管理人员,你要在节点上安装来自对应硬件厂商的 GPU 驱动程序,并运行来自 GPU 厂商的对应的设备插件。
我是阳明
2021/10/20
2.5K1
java json decode 中文_关于json_decode乱码及NULL的解决方法「建议收藏」
写接口的同学应该会经常遇到数据格式的转换,这时候必不可少的两个函数就是json_encode()和json_decode()。
全栈程序员站长
2022/09/09
2.3K0
使用VBA在PPT上调色
这又是VBA应用的一个经典例子。不需要太多的代码,仅仅几句VBA就能实现幻灯片放映过程中与用户交互的功能,太方便了。
fanjy
2023/08/29
3510
使用VBA在PPT上调色
json_decode的结果是null
突然发现一个接口出了问题,经过排查之后发现是json_decode($str,true)的问题,返回竟然是null。这个问题大家可能都碰到过,出现问题的原因就那么几种,再次记录一下吧
全栈程序员站长
2022/09/09
1.1K0
在Windows上调试iPhone/iPad的safari浏览器
在安卓上面可以使用adb链接电脑,使用Chrome Inspect进行调试网页(QQ/微信的x5内核也可以),但是自从换了iPhone之后就没有这个乐趣了,所以我便开始摸索起来如果使用Chrome Inspect来调试safari浏览器(因为iPhone上面的QQ/微信没有x5内核,所以只能调试safari了)
用砖头敲代码
2023/03/25
4.3K0
在Windows上调试iPhone/iPad的safari浏览器
net.sf.json.JSONException: null object_json数组转json对象
在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,同时也易于机器解析和生成、易于理解、阅读和撰写,而且Json采用完全独立于语言的文本格式,这使得Json成为理想的数据交换语言。 JSON建构于两种结构:
全栈程序员站长
2022/11/08
6K0
net.sf.json.JSONException: null object_json数组转json对象
visual studio发生了未处理的异常_打印显示灾难性故障
故障说明:使用vs2010时,由于文件创建MFC类时,移除文件后重新创建正确的基类,覆盖之前创建的文件造成,在“解决方案资源管理器”点击“cpp”文件弹出该提示。
全栈程序员站长
2022/09/29
9320
visual studio发生了未处理的异常_打印显示灾难性故障
Spring+dubbo+mybatis出现NoSuchMethodError和MutablePropertyValues.add异常
Spring+mybatis3+ dubbo整合下,出现以下异常。在此问题上花费了两个多小时,终于查到原因。
程序新视界
2022/05/06
3500
Retrofit 在 JSON 反序列化的时候提示 UnrecognizedPropertyException 异常
这是因为 retrofit 在反序列化的时候,如果没有找到对应的对象名,将会报错。
HoneyMoose
2023/04/25
5180
Retrofit 在 JSON 反序列化的时候提示 UnrecognizedPropertyException 异常
map key为null_mybatis json
本博主之前一直是网络资源的索取者,本着开源精神愿意把自己在开发过程中遇到过的问题以及解决方案分享给大家,这是我的第一篇博客,希望以后能坚持写博客,让大家少走弯路、少踩坑。 废话少说,直入主题! springcloud微服务集成mybatis动态多数据源在网上有很多文章可以搜到,这里就不重复造轮子了。 如题,网上的很多解决方案比如: 尝试在application.yml 文件中配置 mybatis:callSettersOnNulls:true,对于springboot启动加载yml的单一数据源是有效的,但是在动态多数据源的情况下,是需要自己手动增加数据源配置类:DataSourceConfig.java,并且需要在启动类加上了@SpringBootApplication(exclude ={DataSourceAutoConfiguration.class})注解。 因此,上述解决方案就没用了,下面给出我的解决方案,亲测有效: 1.xml文件
全栈程序员站长
2022/11/10
1.2K0
Jetson上调用多个USB摄像头的方法
日前有朋友在 Xavier Orion 上要调用3个USB摄像头,发现只能正常启动2个,感到有些困扰,是否Jetson设备有数量限制? 其实问题的症结在于这位朋友使用OpenCV的方式调用,这种方式虽然上手容易,但是对资源消耗程度比较大,也需要开发者对摄像头一些硬件参数有足够深入的掌握,否则出错率较高。 为了协助更多开发者能有效用起Jetson上的计算资源,这里提供两种能同时调用4个不同规格USB摄像头的方法: 1. 使用英伟达”Hello AI World” 项目的videoSource()函数: 项目
GPUS Lady
2022/05/12
2.8K0
Jetson上调用多个USB摄像头的方法
WPF 依赖属性绑定不上调试方法
在写 WPF 程序的时候会遇到依赖属性绑定了,但是值没有更新或者没有绑定上的问题,本文告诉大家可以如何调试
林德熙
2020/07/06
1.7K0
SharePoint 2010 在WebPart页面上调用扩展方法报方法未定义的解决方案
SharePoint 2010是基于.NET 3.5的,但是微软一直是神坑,页面前台居然不支持扩展方法,也就是你可以在后台代码里面使用扩展方法,但是不能在前台页面 上逍遥,否则会打回原型,比如在WebPart页面上加入如下代码:
雪雁-心莱科技
2018/12/27
1.2K0
当我们在分析异常数据时,我们在分析什么
数据异常分析,是数据分析工作中最常见且重要的分析主题,通过一次次的异常分析来明确造成数据波动的原因,建立日常的的运营工作和数据波动之间的相关性以及贡献程度的概念,从而找到促进数据增长的途径,改变数据结果。
小莹莹
2018/07/24
2.4K0
当我们在分析异常数据时,我们在分析什么
java.lang.NoSuchMethodError
NoSuchMethodError是一个运行时错误,在编译时一般不会出现这个错误。
Java廖志伟
2022/09/29
1K0
Jar包冲突及java.lang.NoSuchMethodError异常解决方案
在编码过程中,往往会遇到jar包冲突的问题。问题的表现特征一般都是抛出java.lang.NoSuchMethodError异常。那么,今天就聊聊怎么解决此类问题。
程序新视界
2022/11/30
1.3K0
php json_decode 返回 null 乱码问题
编码错乱的昵称存在json字符串里,php调用json_decode(xxx, true) 失败,返回null的问题。
shirishiyue
2020/01/01
3.4K0

相似问题

未处理的异常: NoSuchMethodError:在null上调用了方法“setString”

128

未处理的异常: NoSuchMethodError:在null上调用了方法“findAncestorStateOfType”

137

未处理的异常: NoSuchMethodError:在null上调用了方法“validate”

218

未处理的异常: NoSuchMethodError:在null上调用了方法'map‘

18

未处理的异常: NoSuchMethodError:在null上调用了方法'add‘。?

117
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
社区富文本编辑器全新改版!诚邀体验~
全新交互,全新视觉,新增快捷键、悬浮工具栏、高亮块等功能并同时优化现有功能,全面提升创作效率和体验
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文