[英]Java parse Json expected double quote issue
我正在發送以下 json 到休息端點:
{"test":
{
"regisration":{
"id":"22",
"birthdate":"1990-06-01T23:00:00.000Z"
},
"registrationarray":[
{
"id":"22",
"birthdate":"1990-06-01T23:00:00.000Z"
}
]
}
}
我在 Spring Boot 控制器中收到 json 為:
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody Map<String, Object> data) {
Map<String,Object> map = new HashMap<String,Object>();
ObjectMapper mapper2 = new ObjectMapper();
// mapper2.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
try {
map = mapper2.readValue(data.get("registration").toString(),
new TypeReference<HashMap<String,Object>>(){});
logger.info("");
將toString()
應用於data.get("test")
我將字段名周圍的所有雙引號都去掉了,所以我得到:
com.fasterxml.jackson.core.JsonParseException: Unexpected character ('r' (code 109)): was expecting double-quote to start field name
也有人知道為什么我的:
在我的 json 中的字段名稱更改為=
?
我的 java 后端項目中有一個類Registration
。 我想解析我從前端獲得的 json 字符串到注冊對象。 我應該有登記對象mainperson
和登記對象數組用於children
您正在嘗試readValue
Map.toString()
返回值的值。 方法Map.toString()
返回值為{key=value}
,因此它不是 JSON 並且無法使用ObjectMapper
進行解析。
不知道你為什么要跳過這樣的圈套。 只需投射地圖值:
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody Map<String, Object> data) {
Map<String,Object> map = (Map) data.get("registration");
// code here
}
更好的是,讓 Spring/Jackson 將 JSON 映射到結構化數據。
class RegisterRequest {
private Registration registration;
// getters and setters
}
class Registration {
private Person mainperson;
private List<Person> children;
// getters and setters
}
class Person {
private String id;
private Instant birthdate; // should be LocalDate, but input data has time of day and time zone offsets
// getters and setters
}
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody RegisterRequest request) {
Registration registration = request.geRegistration();
// code here
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.