Java 解析 Json 预期的双引号问题

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 引导控制器中收到 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 后端项目中有一个 class Registration。我想解析从前端到注册对象的 json 字符串。我应该有 mainperson 的注册对象和 children

的注册对象数组

您正在尝试 readValueMap.toString() 个返回值。方法Map.toString()returns的值是{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
}