tamtoum1987 tamtoum1987 - 6 months ago 54
Android Question

Deserialize a JSON file that has a key variable jackson map ObjectMapper

I have JSON like this:

{
"flux":{
"1400364000":{
"Optaf_matchdata":{
"uid":"749674", "fk_comp_id":"2414", "comp_id":"112", "saisonid":"2013", "temps":null, "matchday":"40"
}
},
"1400104800":{
"Optaf_matchdata":{
"uid":"749670", "fk_comp_id":"2414", "comp_id":"112", "saisonid":"2013", "temps":null, "matchday":"39"
}
}
}
}


The problem is that the keys
1400364000
and
1400104800
are variable. How can I put this in a
@JsonProperty
, when I don't have the name?

I can retrieve those key 1400364000, 1400104800 separately. How can I retrieve the
Optaf_matchdata
from the
1400364000
key, for example?

Answer

I resolve this by add a customer Deserialize like this:

 @JsonIgnoreProperties(ignoreUnknown = true)
public class CalendarResultsDto {
@JsonDeserialize(using=JsonMatchDeserialize.class)
@JsonProperty(value="flux")

So after that a return a Map witch String it's the key. JsonMatchDeserialize.java:

public class JsonMatchDeserialize extends JsonDeserializer> {

@Override
public Map<String, CalendarMatchDataDto> deserialize(JsonParser jsonParser, DeserializationContext deserializationContext)
        throws IOException, JsonProcessingException {

    Map<String, CalendarMatchDataDto> mapToReturn = new  HashMap<String, CalendarMatchDataDto>();
    JSONObject flux;
    try {
        flux = new JSONObject(jsonParser.getValueAsString());
        ObjectMapper mapper = new ObjectMapper();
         Iterator<String> iter = flux.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                try {
                    Object value = flux.get(key);
                    CalendarMatchDataDto calendarMatchDataDto =  mapper.readValue(value.toString(), CalendarMatchDataDto.class); 
                    if(key!=null && calendarMatchDataDto!=null)
                        mapToReturn.put(key, calendarMatchDataDto);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
    } catch (JSONException e1) {
        e1.printStackTrace();
    }




    return mapToReturn;



}

and CalendarMatchDataDto.java

    public class CalendarMatchDataDto {

@JsonProperty(value="Optaf_matchdata")
public MatchDto matchDto ;
       }
Comments