2016-09-20 98 views
2

我有一个类如下。在Spring中将Requestbody映射到JSONObject

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,它实际上没有这些字段或相关设置程序,所以它最终抛出Unrecognized field "hello" (Class JSONObject), not marked as ignorable at [Source: [email protected]; line: 31, column: 18]

+0

'地图<字符串,对象>'的JSON对象? – chrylis

+0

我已经成功地将'JsonNode'映射到了顶层。当你把你的jsonobject改成jsonnode时它工作吗? –

回答

0

从传入请求形成对象时忽略数据属性。

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

和后创建从所述数据串

 @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 
} 
+0

我曾尝试过@ @ JsonIgnore。没有工作。它与@ jsonignore不同吗? –

+0

对不起,这是一个打字错误,你有没有尝试第二种方法? – Priyamal