EXCEPTION -com.google.gson.stream。MalformedJsonException:第1行第26列未终止的对象path $.[0]. state ">
这是我的POST请求当数据是对象时,id &资源是字符串
private String id;
private String resourceName;
private Object data;
{
"id": "150",
"resourceName": "Fabrik-Resource",
"data": {
"RECORD": [
{
"STATE": "TORONTO CITY"
},
{
"WORK": "SERVICE"
}
]
}
}
Now if i give Space between TORONTO CITY
,它会给我一个异常
com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 26 path $.[0].STATE"
但是当我发送没有空格作为键和值的请求时,如-
"RECORD": [
{
"STATE": "TORONTOCITY"
},
{
"WORK": "SERVICE"
}
]
}
可以,但Space不行
——代码
public ResponseEntity<MasterBlockChainResponse> dummy(@RequestBody(required=false) Masterpayload valueobject) {
Gson gson = new Gson();
MasterBlockChainResponse response = new MasterBlockChainResponse();
Object json = valueobject.getData();
Map<String, Object> map = gson.fromJson(json.toString(), Map.class);
response.setId(valueobject.getId());
response.setResourceName(valueobject.getResourceName());
response.setData(map);
return ResponseEntity.status(HttpStatus.OK).body(response);
}
这是因为:
Map<String, Object> map = gson.fromJson(json.toString(), Map.class);
当你使用toString方法时,它不会将对象转换为合法的JSON对象,尝试使用ObjectMapper。例如
Map<String, Object> map = gson.fromJson(objectMapper.writeValueAsString(json), Map.class);
快速对比差异:
- ToString生产:
{记录=[{状态=多伦多城市},{工作=服务}]}
- writeValueAsString生产:
{"RECORD"[{"STATE"多伦多CITY"},{"已经做完:"SERVICE"]}
代码片段:
Gson gson = new Gson();
Object json = valueobject.getData(); //{RECORD=[{STATE=TORONTO CITY}, {WORK=SERVICE}]}
String jsonString = gson.toJson(json); //{"RECORD":[{"STATE":"TORONTO CITY"},{"WORK":"SERVICE"}]}
Map<String, Object> map = gson.fromJson(jsonString, Map.class); //{RECORD=[{STATE=TORONTO CITY}, {WORK=SERVICE}]}
ArrayList x = (ArrayList) map.get("RECORD");
x.get(0); //{STATE=TORONTO CITY}
x.get(1); //{WORK=SERVICE}
您的对象数据是一个简单的对象,因为您需要这样的数据进行解析:
Data{
List<String> RECORD;
}
所以你的主类:
Class{
String id;
String resourceName;
Data data;
}
而不是映射键值。这样你就不会有任何问题了