user3852209
user3852209

Reputation: 17

How to map dynamic json value to HashMap in Pojo

i use jackson for jax-rs handler

the json member is always same, only 1 of it member have dynamic value ..

this dynamic value could only be "" or json object

json possibility 1

{
    "event":"test",
    "eventInfo": ""
}

json possibility 2

    {
        "event" : "test",
        "eventInfo" : {
             "name" : "abc",
             "last" : "def"
         }
    }

eventInfo value could only be "" or json

i try to map this json to 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);
    }
}

the mapping process happen in 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 fail convert the json as show above to MyBean.java

How to do this?

forgive my english

thanks

Upvotes: 0

Views: 3808

Answers (1)

Syam S
Syam S

Reputation: 8509

The issue is with the setEventInfo() method of MyBean object. In one case the value assigned to it is empty which is treated as string in other case its a linked hashmap. So modify the argument to accept Object. like

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 + "]";
    }
}

Now it should work. Eg

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

Upvotes: 4

Related Questions