简体   繁体   English

将 JSON 转换(反序列化)为 Java POJO Jackson

[英]Convert (Deserializing) JSON to Java POJO Jackson

How to convert below JSON to java HashMap What will be the POJO How map JSON object with Jackson如何将下面的 JSON 转换为 java HashMap 什么是 POJO 如何 map JSON object 和 Jackson

*{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "IBM",
        "3. Last Refreshed": "2020-08-14",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2020-08-14": {
            "1. open": "124.2000",
            "2. high": "125.5600",
            "3. low": "123.9100",
            "4. close": "125.2700",
            "5. volume": "2963753"
        },
        "2020-08-13": {
            "1. open": "125.9600",
            "2. high": "126.3900",
            "3. low": "124.7700",
            "4. close": "125.0300",
            "5. volume": "3171258"
        }
    }
}

This is POJO of Alphavantage:这是 Alphavantage 的 POJO:

public class Alphavantage {
    public MetaData metaData;
    public TimeSeriesDaily timeSeriesDaily;
}

This is POJO of MetaData:这是 MetaData 的 POJO:

public class MetaData{
    public String _1Information;
    public String _2Symbol;
    public String _3LastRefreshed;
    public String _4OutputSize;
    public String _5TimeZone;
}

Pojo of TimeSeriesDaily: TimeSeriesDaily 的 Pojo:

public class TimeSeriesDaily {
    public _20200814 _20200814;
}

This trying to map Pojo using Java Jackson:这尝试使用 Java Jackson map Pojo:

public static Map<Alphavantage,Map<TimeSeriesDaily,Object>> getAlphaData() {        
        RestAssured.baseURI = uri;
        RequestSpecification request = RestAssured.given().log().all();
        Response response = request.get(uri + "/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo");
        String jsonResponse=response.getBody().asString();

        ObjectMapper mapper = new ObjectMapper();
        Map<Alphavantage,Map<TimeSeriesDaily,Object>> data = mapper.readValue(jsonResponse, new TypeReference<Map<Alphavantage,Map<TimeSeriesDaily,Object>>>(){});
        return data;
    }

In order for it to work, the Java object needs to have the exact same name as the JSON field key.为了使其工作,Java object 需要与 JSON 字段键具有完全相同的名称。

So, Jackson would not be able to map 1. Information to _1Information .因此, Jackson 将无法将 map 1. Information传递给_1Information You need to use something like this:你需要使用这样的东西:

@JsonProperty("1. Information")
public String _1Information;

The same holds for every other field.这同样适用于所有其他领域。

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

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