Jackson json 反序列化以整数(原始数据)作为 POJO 的关键

Jackson json deserialization with integer(primitive data) as the key into POJO

在其中一个 API 中,我收到了 Json 响应: 您可以在此处查看此响应示例 Sample Json resopnse

{
    "histogram" : {
        "1" : "12",
        "2" : "20",
        "3" : "50",
        "4" : "90",
        "5" : "10"
     }
}

为了反序列化这个响应,如何编写 POJO 类?

在java中,变量名不允许使用数字,如何将其转换为POJO?

例如,我怎样才能创建这样的东西:

public class MyPOJO {
    Histogram histogram;

    public static class Histogram {
        // I KNOW THIS IS WRONG !!
        String 1;
        String 2;
        String 3;
        String 4;
    }
}

jackson 是否提供任何注释来处理这些?

为此JSON:

{
  "histogram": {
    "1": "12",
    "2": "20",
    "3": "50",
    "4": "90",
    "5": "10"
  }
}

您可以考虑以下方法之一:

使用 Map<String, String> 来保存值

histogram可以解析成Map<String, String>:

public class HistogramWrapper {

    @JsonProperty("histogram")
    private Map<String, String> histogram;

    // Getters and setters omitted
}

使用带有 @JsonProperty

注释的属性

或者,您可以定义一个 Histogram class 并用 @JsonProperty:

注释其属性
public class HistogramWrapper {

    @JsonProperty("histogram")
    private Histogram histogram;

    // Getters and setters omitted
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class Histogram {

    @JsonProperty("1")
    private String _1;

    @JsonProperty("2")
    private String _2;

    @JsonProperty("3")
    private String _3;

    @JsonProperty("4")
    private String _4;

    @JsonProperty("5")
    private String _5;

    // Getters and setters omitted
}

正在解析 JSON

要解析 JSON,请执行以下操作:

ObjectMapper mapper = new ObjectMapper();
String json = "{\"histogram\":{\"1\":\"12\",\"2\":\"20\","
            + "\"3\":\"50\",\"4\":\"90\",\"5\":\"10\"}}";

HistogramWrapper wrapper = mapper.readValue(json, HistogramWrapper.class);

只是对 Cassio 回答的补充,以防你有 Json 这样的回应

{
        "1": 12, 
        "3": 50, 
        "2": 20, 
        "5": 10, 
        "4": 90, 
        "7": 20, 
        "6": 322
}

你可以直接将它们来回序列化和反序列化成一个HashMap。不需要 POJO。

    String jsonString = "{\"1\":\"12\",\"2\":\"20\","
                + "\"3\":\"50\",\"4\":\"90\",\"5\":\"10\"}";

    HashMap<String, Integer> histogramMap;

    histogramMap = (new ObjectMapper()).
    readValue(jsonString, new TypeReference<HashMap<Integer, String>>(){});

这样会直接保存为HashMap