用Jackson将Json子对象转换为HashMap

时间:2017-11-01 13:58:36

标签: java arrays json jackson

我想转换以下json字符串的bpi字段:

{
    "bpi": {
        "2017-10-15": 5697.3917,
        "2017-10-16": 5754.2213,
        "2017-10-17": 5595.235,
        "2017-10-18": 5572.1988,
        "2017-10-19": 5699.5838,
        "2017-10-20": 5984.0863,
        "2017-10-21": 6013.2288,
        "2017-10-22": 5984.9563,
        "2017-10-23": 5895.2988,
        "2017-10-24": 5518.85,
        "2017-10-25": 5733.9038,
        "2017-10-26": 5888.145,
        "2017-10-27": 5767.68,
        "2017-10-28": 5732.825,
        "2017-10-29": 6140.5313,
        "2017-10-30": 6121.8,
        "2017-10-31": 6447.6675
    },
        "disclaimer": "This data was produced from the CoinDesk Bitcoin Price Index. BPI value data returned as USD.",
        "time": {
        "updated": "Nov 1, 2017 13:49:57 UTC",
        "updatedISO": "2017-11-01T13:49:57+00:00"
    }
}

到一个散列图 - 最好是Map<Date, Double>,但Map<String, String>也会这样做(然后我将不得不稍后处理它)。我在某处读到了如何将json数组转换为java数组,但由于所需的数组包含在bpi子字段中,我不知道如何访问它。你可以帮帮我吗?

非常感谢

1 个答案:

答案 0 :(得分:1)

与杰克逊相当直接。首先定义一个类来保存值:

@JsonIgnoreProperties(ignoreUnknown = true)
public class Foo {

    private Map<LocalDate, Double> bpi;

    // Getters and setters ommited
}

然后阅读你的JSON字符串:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

Foo foo = mapper.readValue(json, Foo.class);

或者您也可以使用:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());

JsonNode node = mapper.readTree(json).get("bpi");

ObjectReader reader = mapper.readerFor(new TypeReference<Map<LocalDate, Double>>() {});
Map<LocalDate, Double> bpi = reader.readValue(node);

LocalDate支持来自jackson-datatype-jsr310模块。

添加项目的以下依赖项:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>${jackson.version}</version>
</dependency>

然后在JavaTimeModule个实例中注册ObjectMapper

mapper.registerModule(new JavaTimeModule());

如果您更喜欢使用Date而不是LocalDate,那么您不需要添加任何依赖项,也不需要注册任何模块。在上面的示例中,只需使用Date代替LocalDate。不过,我建议您改用LocalDate