反序列化jackson动态键值

反序列化jackson动态键值

问题描述:

我有一个类似于这个的json结构

I have a json structure similar to this

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

我想将其反序列化为 Java 类

I want to deserialize it to a Java class

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

有任何原生 JACKSON 映射器可以执行此操作,还是我需要为此创建自己的自定义解串器?

There any native JACKSON mappers to do this, or will I need to create my own custom deserializer for this?

我将其读作 Map.class 然后遍历 keyset 以提取值.

I will read it as Map.class and then iterate through keyset to extract values.

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 是固定键.

Assuming Updated and Time are fixed keys.