Home > Mobile >  Spring @RestController double @RequestBody json input
Spring @RestController double @RequestBody json input

Time:10-25

I have implemented the following classes:

public class classA {
    String fieldA;
}

public class classB {
    String fieldB;
}

Then i am using a rest controller having objects of these classes as input:

@RestController
public class MyController {
    @PostMapping(value="/resource")
    public void foo(@RequestBody objA, @RequestBody objB){
        //do stuff
    } 
}

When i invoke the API using the following input:

{
    "objA" : {
        "fieldA" : "valueA"
    },
    "objB" : {
        "fieldB" : "valueB"
    }
}

I get the following error:

org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public void com.classA

Am i missing something on the JSON input?

CodePudding user response:

It's not possible to have multiple @RequestBody. For that usecase you need to write a Wrapperclass:

public class ClassAB {
    ClassB classB;
    ClassA classA;
}

and then use it in the RestController:

@RestController
public class MyController {
    @PostMapping(value="/resource")
    public void foo(@RequestBody ClassAB ab){
        // ab.classB
        // ab.classA
        // do stuff
    } 
}

CodePudding user response:

You cannot pass more than one request body, you need to pass an Array of objects or have an outer object containing the two objects, or you could use a map, a JSONObject ecc.

There are many ways to do this depending on your use case.

  • Related