今天使用json字符串转对象的时候,遇到一个错误。所以做一个总结
Exception in thread "main" com.google.gson.JsonSyntaxException: com.google.gson.stream.MalformedJsonException: Expected literal value at line 1 column 28
这个错误是json字符串有存在问题。
我有一个这样子的字符串
String httpResponse="{\"code\":\"0\",\"success\":true,\"data\":{\"IsSuccess\":1,\"FailReason\":\"\",\"RefundOrderId\":\"161017132456273328\",\"ErrorCode\":\"\"},\"message\":\"\",\"requestid\":\"8ef58d60-7d72-46ec-b16a-3692b30d4a5c\"}";
Refund response=new Gson().fromJson(httpResponse, Refund.class);
BaseResponse baseResponse=new BaseResponse();
baseResponse.setCode(response.getCode());
baseResponse.setMessage(response.getMessage());
baseResponse.setSuccess(response.isSuccess());
baseResponse.setData(response.getData().toString());//改成baseResponse.setData(new Gson().toJson(response.getData()));
其实这里的json字符串变成了{IsSuccess=1.0, FailReason=, RefundOrderId=161017132456273328, ErrorCode=}这样子。
RefundApplyResponse res1=new Gson().fromJson(baseResponse.getData(),RefundApplyResponse.class);
因为我们这边的代码都是要先转换成BaseResponse的,然后在转换成对应的对象,我这里只是吧代码简单的复制出来了。还有很多没贴
一执行这段代码。就报错
所以用上面的Data的json字符串,去转换对象,肯定是要报错的。
那要怎么解决呢?怎么在Data那里为空的数据,""双引号不会自动去掉
所以要在生成错误Json字符串,那里修改:
baseResponse.setData(new Gson().toJson(response.getData()));
打印的json字符串为:{"IsSuccess":1.0,"FailReason":"","RefundOrderId":"161017132456273328","ErrorCode":""}
这样子的话,就可以了