将json转换(反序列化)为java pojo

8xiog9wr  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(381)

如何将下面的json转换为java hashmap什么是pojo how map json对象与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"
        }
    }
}

这是alphavantage的pojo:

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

这是元数据的pojo:

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

时间顺序:

public class TimeSeriesDaily {
    public _20200814 _20200814;
}

尝试使用java jacksonMappojo:

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;
    }
6g8kf2rb

6g8kf2rb1#

为了工作,java对象需要与json字段键具有完全相同的名称。
所以,Jackson无法绘制Map 1. Information_1Information . 你需要用这样的方法:

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

其他领域也是如此。

相关问题