如何将动态json值映射到Pojo中的HashMap

时间:2014-07-18 09:26:07

标签: java json jackson jax-rs

我使用jackson作为jax-rs处理程序

json成员总是相同的,只有其中一个成员具有动态值..

此动态值只能是“”或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失败

怎么做?

原谅我的英语

感谢

1 个答案:

答案 0 :(得分:3)

问题在于MyBean对象的setEventInfo()方法。在一种情况下,分配给它的值是空的,在其他情况下它被视为字符串,它是一个链接的散列映射。因此修改参数以接受Object。像

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(Object eventObject) {
        if(eventObject instanceof Map){
            this.eventInfo.putAll((Map<String, String>) eventObject);
        }
    }

    @Override
    public String toString() {
        return "MyBean [event=" + event + ", eventInfo=" + eventInfo + "]";
    }
}

现在它应该工作了。例如

String json1 = "{ \"event\":\"test\", \"eventInfo\": \"\" }";
String json2 = "{\"event\":\"test\",\"eventInfo\":{\"name\":\"abc\",\"last\":\"def\"}}";
ObjectMapper mapper = new ObjectMapper();
try {
    MyBean bean1 = mapper.readValue(json1, MyBean.class);
    System.out.println(bean1);
    MyBean bean2 = mapper.readValue(json2, MyBean.class);
    System.out.println(bean2);
} catch (IOException e) {
    e.printStackTrace();
}