开发者

Binding the nested json to @RequestBody object using Jackson converter

I have two classes

public class Parent {
    private String name;
    private int age;
    private ArrayList<Child> children = new ArrayList<Child>();
    //Setters and getter to follow..
}

public Class Child {
    private String name;
    private int age;
}

Spring config includes:

<bean id="jsonMessageConverter"
    class="org.springframework.http.converter.json.MappingJ开发者_运维问答acksonHttpMessageConverter" />

<bean
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <ref bean="jsonMessageConverter" />
        </list>
    </property>
</bean>  

Controller looks like the following:

@RequestMapping(value = "/parents", 
                method = RequestMethod.POST, 
                headers="Content-Type=application/json")
public @ResponseBody Parent add(@RequestBody Parent parent, Model model) {

    logger.debug("Received request to add a parent");
    Parent tempParent = parentService.add(parent); // This will persist the parent object to the DB.. (Helper class)
    return tempContract;
}

In a normal circumstances, it should bind the incoming json to Parent and return the Parent as a Json in the response. And it's giving me the exception: "The request sent by the client was syntactically incorrect." with the following input Json:

{
    "name" : "foo",
    "age" : "45",
    "children" : [ 
      {
         "name" : "bar",
         "age" : "15""
      },
      {
         "name" : "baz",
         "age" : "10""        
      }
    ]
} 

So tried changing the json and it works just fine binding both @RequestBody and @ResponseBody with the following formats:

{
    "name" : "foo",
    "age" : "45",
    "children" : []
}

and

{
    "name" : "foo",
    "age" : "45",
    "children" : [ 
      {}
    ]
} 

So I'm assuming there is something wrong biding the actual child class or with the way I'm passing the Json object wrt Child object. Could someone please help me out here. Also, is it suggested to use

 private ArrayList<HashMap<String, Child>> children = new ArrayList<HashMap<String, Child>>();

instead of

private ArrayList<Child> children = new ArrayList<Child>();

Thank you.


The updated JSON example in the question is still invalid. I recommend checking JSON examples with JSONLint.com.

Following is an example of using Jackson to deserialize a corrected version of the JSON into the same Parent/Child class structure in the current version of the question.

import java.util.ArrayList;

import org.codehaus.jackson.map.ObjectMapper;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
/*
{
    "name": "foo",
    "age": "45",
    "children": [
        {
            "name": "bar",
            "age": "15"
        },
        {
            "name": "baz",
            "age": "10"
        }
    ]
}
 */
    String jsonInput = "{\"name\":\"foo\",\"age\":\"45\",\"children\":[{\"name\":\"bar\",\"age\":\"15\"},{\"name\":\"baz\",\"age\":\"10\"}]}";

    ObjectMapper mapper = new ObjectMapper();
    Parent parent = mapper.readValue(jsonInput, Parent.class);
    System.out.println(mapper.writeValueAsString(parent));
    // output:
    // {"name":"foo","age":45,"children":[{"name":"bar","age":15},{"name":"baz","age":10}]}
  }
}

class Parent
{
  public String name;
  public int age;
  public ArrayList<Child> children = new ArrayList<Child>();
}

class Child
{
  public String name;
  public int age;
}

Is it possible that the message about the syntax error is just that: a message about a syntax error? Specifically, about the invalid JSON input? Or is the real JSON actually valid, and just the examples in the question are invalid?

"is it suggested to use ArrayList<HashMap<String, Child>>"

No. The JSON structure doesn't match ArrayList<HashMap<String, Child>>. So, I wouldn't try to use it.


One would first guess the stray quotes after 15 and 10 in the children's ages. What's generating your input?


The issue was fixed by adding below logic.

public @ResponseBody String  saveDrug(@RequestBody DrugListJsonRequest drugListCriterion) {}

Here your Java class DrugListJsonRequest should extend

HashMap<String,ArrayList<DrugListCriterion>>

It doesn't require a any methods and constructors.

public class DrugListJsonRequest extends HashMap<String,ArrayList<DrugListCriterion>>{}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜