将Requestbody映射到Spring中的JSONObject

时间:2016-09-20 09:11:11

标签: java spring

我有一个课程如下。

class ExampleBean{
   public String Name;
   public JSONObject data;
}

我有@GET处理程序,如下所示:

@GET
@Consumes({MediaType.APPLICATION_JSON})
public Response getData(ExampleBean dataBean)
{
    // some usage code here
}

我希望将json映射到ExmampleBean:

{
  "Name":"Example",
  "data":{
       "hello":"world",
       "some":"value"
   }
 }

如果data是一个有两个名为hellosome的公共字段的类型,那么一切都很有效。但由于data是一个JSONObject,它实际上没有那些字段或相关的setter,它最终会抛出Unrecognized field "hello" (Class JSONObject), not marked as ignorable at [Source: org.apache.catalina.connector.CoyoteInputStream@17b9a4bf; line: 31, column: 18]

2 个答案:

答案 0 :(得分:0)

在从传入请求中形成对象时忽略data属性。

class ExampleBean{
   public String Name;
   @JsonIgnore
   public JSONObject data;
}

并更改其余服务以接受来自传入请求的数据作为参数。

@GET
@Consumes({MediaType.APPLICATION_JSON})
public Response getData(@RequestBody ExampleBean dataBean,RequestParam("data") String data)
{

 JSONParser parser = new JSONParser();
 JSONObject json = (JSONObject) parser.parse(data);
    // some usage code here
}

或者您可以将JsonObject data的数据类型更改为String,并从传入的请求中形成object

 class ExampleBean{
 public String Name;
 public String data;
 }

然后从数据字符串

创建一个Json对象
      @GET
@Consumes({MediaType.APPLICATION_JSON})
public Response getData(@RequestBody ExampleBean dataBean)
{

 JSONParser parser = new JSONParser();
 JSONObject json = (JSONObject) parser.parse(dataBean.data);
    // converting the string data to jsonobject
}

答案 1 :(得分:0)

尝试使用JsonNode。它正在工作。

类: com.fasterxml.jackson.databind.JsonNode

相关问题