你也遇到JSONException:create instance error, null...问题啦?
近期在工作中踩到的坑,返回结果使用Result<T>
封装,结果踩了两个FastJson与构造方法的大坑,分享下,注意别踩到相同的坑。
1. 测试代码
- 创建了
Result<String>
对象,序列化为JSON字符串 - 将JSON字符串反序列化为
Result<String>
对象public static void main(String[] args) {// 创建对象Result<String> result = new Result<String>().setRet(-1).setData(null).setError(new Result.Error(404).addErrorDetail("id", 9, "resource.not.found"));// 将对象序列化为JSON字符串String resultJson = JSONObject.toJSONString(result,SerializerFeature.WriteMapNullValue,SerializerFeature.PrettyFormat);System.out.println(resultJson); // 反序列化Result<String> resultFromJson = JSON.parseObject(resultJson, new TypeReference<Result<String>>() {});System.out.println(resultFromJson);}
序列化后的JSON字符串
{"data":null,"error":{"code":404,"details":[{"data":9,"field":"id","msg":"resource.not.found"}]},"ret":-1 }
和构造方法有关。
creatorConstructor
被确定为Error(int code)
这个构造方法,而这个构造方法就只有int code
这个一个参数,在反序列化创建Result.Error
时,就这完成了code
字段的赋值,而没有反序列化details
字段。
解决方案
Result.Error
增加构造方法Error(int code, List<ErrorDetail> details)
Result<T>增加无参构造方法
至此,问题解决。
小结
- JSON反序列化与构造方法密切相关,推荐每个类都提供无参构造方法
- 如果某个类从设计上不适合提供无参构造方法,需要特别注意以上两个问题。推荐提供全参构造方法。
相关类定义
正确的Result<T>
import lombok.Data;
import lombok.experimental.Accessors;import java.util.ArrayList;
import java.util.List;@Data
@Accessors(chain = true)
public class Result<T> {/*** ret >= 0 success;* ret < 0 error;*/private int ret;private T data;private Error error;@Data@Accessors(chain = true)public static class Error {private int code;private List<ErrorDetail> details;public Error(int code) {this.code = code;this.details = new ArrayList<>();}/*** 特别注意,改构造方法千万不要放到上一个构造方法前,否则会导致FastJson反序列出问题。* <p>* public Error(CmnCode code) {* this.code = code.getCode();* this.details = new ArrayList<>();* }*/public Error(int code, List<ErrorDetail> details) {this.code = code;if (null == details) {this.details = new ArrayList<>();} else {this.details = details;}}public Error addErrorDetail(String msg) {this.details.add(new Result.ErrorDetail().setMsg(msg));return this;}public Error addErrorDetail(String field, String msg) {this.details.add(new Result.ErrorDetail().setField(field).setMsg(msg));return this;}public Error addErrorDetail(Object data, String msg) {this.details.add(new Result.ErrorDetail().setData(data).setMsg(msg));return this;}public Error addErrorDetail(String field, Object data, String msg) {this.details.add(new Result.ErrorDetail().setField(field).setData(data).setMsg(msg));return this;}}@Data@Accessors(chain = true)public static class ErrorDetail {/*** error field;*/private String field;/*** error field value;*/private Object data;/*** error field message;*/private String msg;}
}
CmnCode枚举
import java.io.Serializable;public enum CmnCode implements Serializable {/*** ok*/OK(200),BAD_REQUEST(400),UNAUTHORIZED(401),FORBIDDEN(403),NOT_FOUND(404),METHOD_NOT_ALLOWED(405),NOT_ACCEPTABLE(406),CONFLICT(409),PRECONDITION_FAILED(412),UNSUPPORTED_MEDIA_TYPE(415),PROTOCOL_NOT_MATCH(444),INTERNAL_ERROR(500),GATEWAY_ERROR(502),SERVICE_UNAVAILABLE(503),GATEWAY_TIMEOUT(504);private int code;CmnCode(int code) {this.code = code;}public static CmnCode fromHttpStatus(int httpStatus) {for (CmnCode cmnCode : values()) {if (cmnCode.getCode() == httpStatus) {return cmnCode;}}return INTERNAL_ERROR;}public int getCode() {return code;}public CmnCode setCode(int code) {this.code = code;return this;}
}
引发问题的Result<T>
@Data
@Accessors(chain = true)
public class Result<T> {/*** ret >= 0 success;* ret < 0 error;*/private int ret;private T data;private Error error;@Data@Accessors(chain = true)public static class Error {private int code;private List<ErrorDetail> details;public Error(CmnCode cmnCode) {this.code = cmnCode.getCode();this.details = new ArrayList<>();}public Error(int code) {this.code = code;this.details = new ArrayList<>();}}
}
你也遇到JSONException:create instance error, null...问题啦?相关推荐
- com.alibaba.fastjson.JSONException: create instanc
2019独角兽企业重金招聘Python工程师标准>>> 不能以内部类的形式,使用parseObject方法,会报:com.alibaba.fastjson.JSONException ...
- 阿里旺旺出现create DOMDocument instance error
最近出现的一个问题,电脑刚开始安装的是360管家,后面卸载,装的金山,就一直出现一个问题旺旺出现create DOMDocument instance error ,各种卸载,各种杀毒,都没有解决,在 ...
- Exception in thread main com.alibaba.fastjson.JSONException: create asm serializer error
今天测试代码发现转为json格式的代码一点问题都没有,但是报了下面的错 Exception in thread "main" com.alibaba.fastjson.JSONEx ...
- MFC多线程失败:Create Instance failed
最近在使用VS2010处理MFC多线程时,按照如下方式编写: AfxBeginThread(threadFunction,NULL); //线程创建函数 UIN ...
- android sqlite 创建空表,sqlite3在android中创建表错误(sqlite3 create table error in android)...
sqlite3在android中创建表错误(sqlite3 create table error in android) 我试图在android中使用sqlite3创建表我的开放助手是这样的: pub ...
- Android studio之编译出现 Error:null value in entry: outputDirectory=null
1.问题 昨天编译好好的,今天编译无缘无故报下面这个错 Error:null value in entry: outputDirectory=null 2.解决办法 cd 到项目的根目录去,然后删除. ...
- error: 'NULL' was not declared in this scope
编译时出现这个错误: error: 'NULL' was not declared in this scope 解决方式: 在文件开头添加如下代码: #include <stddef.h> ...
- 谷歌支付:In-app billing error: Null data in IAB activity result (-1002 )
今天测试谷歌支付又遇到一个新坑,在小米手机进行的测试调用谷歌支付的时候支付弹窗一直不出来,打印结果显示 In-app billing error: Null data in IAB activity ...
- o2o实战报错:addShopImg error:null / character to be escaped is missing
操作系统:Window10 1.在做到ShopServiceTest的JUnit测试时,报出错误信息:addShopImg error:null 如下: 解决办法:修改PathUtil.java的配置 ...
最新文章
- CMAKE支持c++11的两种方式
- 用命令行非交互改密码
- 关于办技术线下社区的一些思考
- Linux0.11中对文本文件进行修改的策略
- 简明python教程购买-简明python教程哪版(python看什么书)
- 使用rabbitMQ实现数据同步
- html5 markdown,Markdown常用语法
- java ee自动生成编码_EE Servlet 3:在Servlet中生成HTML输出
- java二叉树删除子树_132-BST删除有一颗子树的结点
- 神经网络与深度学习——TensorFlow2.0实战(笔记)(二)(包管理和环境管理)
- seqkit根据基因id_Microwell-Seq
- Bing Maps进阶系列六:使用Silverlight剪切(Clip)特性实现Bing Maps的迷你小地图
- 什么情况下document.write会覆盖页面及覆盖原理解释
- Linux安装GCC方法
- 哈理工OJ—1309入侵检测(字符串处--剪枝)
- 新曼联:弗格森制造 第七章 欧战惊喜 之4 安心之选:埃尔文
- 微信 android 点赞,朋友圈点赞生成器安卓-微信朋友圈点赞生成器2020安卓最新版app预约 v1.0-优盘手机站...
- 使用谷歌API将任意语言翻译成英文
- 隐马尔可夫模型(三): 算法分类、解决方法
- like功能以及check功能