java - 反序列化具有键变量 jackson map ObjectMapper 的 JSON 文件

标签 java android jackson mapper

我有这样的 JSON:

{
    "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"
            }
        }
    }
}

问题在于键 14003640001400104800 是可变的。当我没有名称时,如何将其放入 @JsonProperty

我可以分别检索这些 key 1400364000、1400104800。例如,如何从 1400364000 键中检索 Optaf_matchdata

最佳答案

我通过添加客户反序列化来解决这个问题:

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

所以在那之后返回一个 Map 女巫字符串它是关键。 JsonMatchDeserialize.java:

公共(public)类 JsonMatchDeserialize 扩展 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;



}

和 CalendarMatchDataDto.java

    public class CalendarMatchDataDto {

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

关于java - 反序列化具有键变量 jackson map ObjectMapper 的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23388115/

相关文章:

java - org.postgresql.util.PSQLException : ERROR: maximum number of prepared transactions reached

android - java.io.IOException : com. android.jack.api.v01.CompilationException: 编译失败

android - Play 商店应用本地化

java - jackson 接受否定日期

java - Jackson 在对象创建期间忽略字段

java - 旋转数次后在给定索引处查找元素

java - Android Spinner 填充对象

java - 意外的多线程结果和计时

java - android动画图片变化

java - Spring Boot 升级后 Jackson 序列化不起作用