spring controller json receive json List

2019-07-17 13:29发布

问题:

I do post below json contain

{"testListObject":[{"testText":"bbb","testDate":"02.01.2011 00:00:00.000"},{"testText":"aaa","testDate":"01.01.2011 00:00:00.000"}]}

in my spring controller i have

@RequestMapping(value = "/post/tester/", method = RequestMethod.POST)
 public @ResponseBody String postItinerary(@ModelAttribute("testListObject") TestList testList) throws IOException {


    System.out.println("1="+testList); //ok
    System.out.println("2="+testList.childListObject); //print null
}

Any idea why i getting null for List childListObject ?

my pojo look like below

    public class TestList (){

    public List<ChildObject> childListObject;

//get and set
    }


    public class ChildObject(){

    public String testText;
    public String testDate;
//get and set    
}

回答1:

@ModelAttribute invokes the web data binder. It's looking for ordinary post method parameters (e.g., param key - "childListObject[0].testText" param value "bbb") to bind onto your object.
For deserializing JSON into an object, you want to use @RequestBody to invoke the serializer.

Also, your JSON doesn't seem to match the obect. You JSON is just an array without the wrapper object, so if you submitted that as your request, the method parameter would be just a List.



回答2:

Have you configured org.springframework.http.converter.json.MappingJacksonHttpMessageConverter in your setting xml?