简体   繁体   English

如何将 map 几个 json 字段转换为单个 java Z1D78DC8ED51214E518B5114AE24490?

[英]How to map several json fields to a single java map?

How to map this JSON to this Java object where the habits Map will have the keys HabitName.FITNESS and HabitName.MATHEMATICS with the corresponding values? How to map this JSON to this Java object where the habits Map will have the keys HabitName.FITNESS and HabitName.MATHEMATICS with the corresponding values? Constructor, getters and setters are omitted to readability.构造函数、getter 和 setter 被省略以提高可读性。

{
  "habits": {
    "fitness": {
      "duration": "1 week",
      "score": "2.1"
    },
    "mathematics": {
      "duration": "2 weeks",
      "score": "2.4"
    }
  }
}
public class IncomingJson {
  Map<HabitName, HabitDesc> habits;

  public enum HabitName {
    @JsonProperty("fitness") FITNESS,
    @JsonProperty("mathematics") MATHEMATICS
  }
  
  public static class HabitDesc {
    String duration;
    String score;
  }
}

At runtime I get the following Exception:在运行时我得到以下异常:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "fitness" (class IncomingJson), not marked as ignorable (one known property: "habits") 

The solution was close.解决方案很接近。 You can deserialize this JSON into the following Java class easily.您可以轻松地将此 JSON 反序列化为以下 Java class。

{
    "root" : {
        "habits": {
            "fitness": {
                "duration": "1 week",
                "score": "2.1"
            },
            "mathematics": {
                "duration": "2 weeks",
                "score": "2.4"
            }
        }
    }
}
@Getter
@RequiredArgsConstructor
@JsonRootName("root")
publi class Habits {
    private final Map<HabitName, HabitDesc> habits = new HashMap<>();
    public enum HabitName {
        @JsonProperty("fitness") FITNESS,
        @JsonProperty("mathematics") MATHEMATICS
    }
    @Getter
    @RequiredArgsConstructor
    public static class HabitDesc {
        @JsonProperty("duration") private final String duration;
        @JsonProperty("score") private final String score;
    }
}

IMPORTANT : The above class relies on lombok.anyconstructor.addconstructorproperties=true in the lombok.config file in the same package as Habits.class .重要提示:上述 class 依赖于lombok.anyconstructor.addconstructorproperties=true在同一 package 中的lombok.config文件中的Habits.ZA2F2ED4F8EBC2CBB4DZC21A29

So your deserialization code will look like this所以你的反序列化代码看起来像这样

var objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Habits = objectMapper.readValue(JSON_STRING, Habits.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM