EXCEPTION - com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 26 path $.[0].STATE"
This is My POST REQUEST. Where Data is an Object, id & resource is String
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
,It will give me an exception
com.google.gson.stream.MalformedJsonException: Unterminated object at line 1 column 26 path $.[0].STATE"
but when I send requests without spaces as keys and values like -
"RECORD": [
{
"STATE": "TORONTOCITY"
},
{
"WORK": "SERVICE"
}
]
}
It work but not with Space
CODE -
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);
}
CodePudding user response:
Your object data is a simple object because you need that data is like this for parsing
Data{
List<String> RECORD;
}
so your principal class
Class{
String id;
String resourceName;
Data data;
}
And not a map key-value. in this way you shouldn't have any problems
CodePudding user response:
Hi this is because of the line:
Map<String, Object> map = gson.fromJson(json.toString(), Map.class);
when you use toString method it doesn't convert the object into a legit JSON Object, try and use ObjectMapper. i.e.
Map<String, Object> map = gson.fromJson(objectMapper.writeValueAsString(json), Map.class);
Quick Comparison of the difference :
- ToString Produces:
{RECORD=[{STATE=TORONTO CITY}, {WORK=SERVICE}]}
- writeValueAsString Produces:
{"RECORD":[{"STATE":"TORONTO CITY"},{"WORK":"SERVICE"}]}