문제

I am new to SpringBoot and I noticed the default message converter doesn't deserialise nested objects.

public class Area {
   public String name;
   public Country country;
}

public class Country {
    public String name;
}

If I POST this json to the Server {"name":"someplace", "country":[{"name":"somecountry"}]} nothing happens.

Can you tell me how I can make this work so that the @RequestBody Area object is assembled correctly?

도움이 되었습니까?

해결책

The request body that you show us is incorrect, there are some extra square brackets inside the country value.

The request body should be like this:

 {
     "name": "someplace",
     "country": {
         "name": "somecountry"
     }
 }

The following setup worked for me, in case you need some reference:

@EnableAutoConfiguration
@ComponentScan
@RestController
public class Main {

    public static void main(String[] args) {
        SpringApplication.run(Main.class, args);
    }

    @RequestMapping(value = "/region", method = RequestMethod.POST)
    public void region(@RequestBody Area area) {
        System.out.println("Received area: " + area);
    }
}

다른 팁

Gabriel is correct that you don't need to do this for your use case, but generally speaking you can add a @Bean of type ObjectMapper and customize it any way you like. (See docs for details.)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top