Search code examples
javajsonwit.ai

Json to Pojo converstion for response from wit.ai


While calling /message endpoint of wit.ai their documentation says they'll send a reply of following format:

 {
"msg_id": "387b8515-0c1d-42a9-aa80-e68b66b66c27",
"_text": "how many people between Tuesday and Friday",
"entities": {
  "metric": [ {
    "metadata": "{'code': 324}",
    "value": "metric_visitor",
    "confidence": 0.9231
  } ],
  "datetime": [ {
    "value": {
      "from": "2014-07-01T00:00:00.000-07:00",
      "to": "2014-07-02T00:00:00.000-07:00"
    },
    "confidence": 1
  }, {
    "value": {
      "from": "2014-07-04T00:00:00.000-07:00",
      "to": "2014-07-05T00:00:00.000-07:00"
    },
    "confidence": 1
  } ]
}

}

Now what I don't understand is that what kind of POJO structure can hold such a response which has almost everything dynamic. AFAIK the entities listed in the json are key value pairs of <String,List<Object>> . Where Object itself is a key value pair where values can be of any type String,float or even another map.

Online Json to Pojo converters can't help in this case as they create classes of key names and these keys are dynamic. Can anyone please help me understand how to handle these kind of jsons?


Solution

  • I kept trying it myself and following structure has worked well so far:

    public class WitMsgResponse {
        @JsonProperty("msg_id")
        String msgId;
    
        @JsonProperty("_text")
        String text;
    
        @JsonProperty("entities")
        public Map<String,List<Map<String,Object>>> entities;
    }
    

    I keep checking instanceof for Object instances since a single key can have multiple kind of object values.