Home > front end >  How to deserialize only certain parts of the POST request body?
How to deserialize only certain parts of the POST request body?

Time:05-19

The following is the entire request body of the POST request

{
    "box": {
        "boxIds": [
            {
                "id": 1
            },
            {
                "id": 2
            }
        ]
    }
}

but only the boxIds key-value pair should be deserialized:

"boxIds": [{"id": 1},{"id": 2}]

Is there a way to implement that using

List<BoxId> boxIds = new ArrayList<>();

in the Box class?

@RestController
public class BoxController {
    @PostMapping("/boxes")
    public Box postBoxes(@RequestBody Box box) {
        // Do something.
        return box;
    }
}
@Data
public class Box {
    // Map<String, Object> box; // Would deserialize entire request body.

    List<BoxId> boxIds = new ArrayList<>();  // Should only deserialize "boxIds": [{"id": 1},{"id": 2}]
    @Data
    static class BoxId {
        private int id;
}

CodePudding user response:

I believe the Spring Data Core @JsonPath annotation will solve your problem.

Here are some links:

Jayway JsonPath github - A reasonable writeup.
Spring Data Commons Reference - only contains a brief mention of @JsonPath
Spring Data JsonPath JavaDoc path

CodePudding user response:

Here's an example,
https://fasterxml.github.io/jackson-annotations/javadoc/2.10/com/fasterxml/jackson/annotation/JsonTypeName.html

    @JsonTypeName("box")
    @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
    public class Box {
    
        List<BoxId> boxIds = new ArrayList<>();
        //getter & setter
           
            static class BoxId {
                 private Integer id;
           //getter & setter
    }


    @PostMapping("/boxes")
    public Box postBoxes(@RequestBody Box box) {
        System.out.println(box.getBoxIds());
        return box;
    }

Console Output:

[BoxId [id=1], BoxId [id=2]]
  • Related