反序列化jackson动态键值

时间:2017-07-14 05:18:49

标签: java spring-boot jackson

我有一个与此类似的json结构

{
  "Byc-yes": { // < code
    "Updated": "week", // < period
    "Time": "12pm" // < time
  },
  "Uop-thp":{
    "Updated": "week",
    "Time": "12pm
  } ,
  ...

我想将它反序列化为Java类

class Updating {
   private String code;
   private String period;
   private String time;
}

有任何本地JACKSON映射器可以执行此操作,还是需要为此创建自己的自定义反序列化器?

1 个答案:

答案 0 :(得分:1)

我会将其读作Map.class,然后遍历键集以提取值。

ObjectMapper objectMapper = new ObjectMapper();
    Map map = objectMapper.readValue(s, Map.class);
    for (Object o : map.keySet()) {
        String key = (String) o;
        System.out.println(key);//prints Byc-yes for first
        Map<String, String> value = (Map<String, String>) map.get(key);
        System.out.println(value); //prints {Updated=week, Time=12pm} for first
        Updating updating = new Updating(key, value.get("Updated"), value.get("Time"));
        System.out.println(updating);
    }

假设UpdatedTime是固定密钥。