使用 Jackson 转换器将嵌套 json 绑定到 @RequestBody 对象

发布于 2024-11-19 22:25:49 字数 2143 浏览 1 评论 0 原文

我有两个类

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 配置包括:

<bean id="jsonMessageConverter"
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />

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

控制器如下所示:

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

在正常情况下,它应该将传入的 json 绑定到 Parent 并在响应中将 Parent 作为 Json 返回。它给了我一个例外:“客户端发送的请求在语法上不正确。”使用以下输入 Json:

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

所以尝试更改 json,它可以很好地使用以下格式绑定 @RequestBody 和 @ResponseBody:

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

所以

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

我假设实际的子类或我的方式有问题将 Json 对象传递给 Child 对象。有人可以帮我吗?另外,是否建议使用

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

而不是

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

谢谢。

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.MappingJacksonHttpMessageConverter" />

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

鞋纸虽美,但不合脚ㄋ〞 2024-11-26 22:25:50

通过添加以下逻辑解决了该问题。

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

这里你的Java类 DrugListJsonRequest 应该扩展

HashMap<String,ArrayList<DrugListCriterion>>

它不需要任何方法和构造函数。

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

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>>{}
你的往事 2024-11-26 22:25:49

问题中更新的 JSON 示例仍然无效。我建议使用 JSONLint.com 检查 JSON 示例。

以下是使用 Jackson 将正确版本的 JSON 反序列化为当前问题版本中相同的父/子类结构的示例。

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

关于语法错误的消息是否有可能只是:关于语法错误的消息?具体来说,关于无效的 JSON 输入?或者真正的 JSON 实际上是有效的,而只是问题中的示例无效?

“是否建议使用ArrayList>

否,JSON结构不匹配ArrayList> 。所以,我不会尝试使用它。

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.

烟沫凡尘 2024-11-26 22:25:49

人们首先会猜测儿童年龄中15岁和10岁之后的杂散引语。是什么产生了你的输入?

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文