Domanda

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?

È stato utile?

Soluzione

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);
    }
}

Altri suggerimenti

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.)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top