【发布时间】:2014-07-18 09:26:06
【问题描述】:
我使用 jackson 作为 jax-rs 处理程序
json 成员总是相同的,只有 1 个成员具有动态值..
这个动态值只能是 "" 或 json 对象
json可能性1
{
"event":"test",
"eventInfo": ""
}
json可能性2
{
"event" : "test",
"eventInfo" : {
"name" : "abc",
"last" : "def"
}
}
eventInfo 值只能是 "" 或 json
我尝试将此 json 映射到 MyBean.java
MyBean.java
public class MyBean{
private String event;
private Map<String, String> eventInfo = new HashMap<String, String>();
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
@JsonAnyGetter
public Map getEventInfo() {
return eventInfo;
}
@JsonAnySetter
public void setEventInfo(String name, String value) {
this.eventInfo.put(name, value);
}
}
映射过程发生在 MyService.java 中
MyService.java
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces("text/plain")
public String receiveClientStatus(MyBean status){
if(!status.getEventInfo().isEmpty()){
String last = status.getEventInfo().get("last").toString() ;
System.err.println( last );
}
return "ok";
}
jackson 无法将上面显示的 json 转换为 MyBean.java
如何做到这一点?
原谅我的英语
谢谢
【问题讨论】:
-
setEventInfo 方法接受字符串值。应该是对象吗?
-
@AlexeyGavrilov 我已经尝试将它作为对象但它也失败了
-
MyBean 看起来不错。你如何调用receiveClientStatus?来自浏览器?
-
@skarist 我使用 JQuery POST,也使用 application/json 作为 contentType,我认为发送 JSON 没有问题,我也在线检查我的 json 验证。我发送的 json 与我展示的两个示例类似。我认为问题是杰克逊无法将我的 json 转换为 MyBean