简体   繁体   中英

Java parse Json expected double quote issue

i am sending following json to rest endpoint:

{"test":
    {
       "regisration":{
          "id":"22",
          "birthdate":"1990-06-01T23:00:00.000Z"
       },
       "registrationarray":[
          {
              "id":"22",
              "birthdate":"1990-06-01T23:00:00.000Z"
          }
       ]
    }
 }

I am receiving the json in spring boot controller as:

@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("");

When applying toString() to data.get("test") i loose all the double quotes around the field-names so then I get:

com.fasterxml.jackson.core.JsonParseException: Unexpected character ('r' (code 109)): was expecting double-quote to start field name

Also anybody knows why all my : after my field-names in my json get changed to = ?

I have a class Registration in my java backend project. And I want to parse the json string i get from frontend to registration objects. I should have Registration object for mainperson and registration object array for children

You are trying to readValue of Map.toString() returning value. Method Map.toString() returns value as {key=value} , so it is not JSON and it cannot be parsed with ObjectMapper .

Don't know why you're jumping through hoops like that. Just cast the map value:

@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody Map<String, Object> data) {
    Map<String,Object> map = (Map) data.get("registration");
    // code here
}

Better yet, have Spring/Jackson map the JSON to structured data.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM