如何在java中合并2个对象

时间:2017-06-16 08:37:51

标签: java

我想将dynamodb数据库表中的JSON数据保存为具有相应值的列名,i,e:

Date = 2017-06-12
Cash Buyer = 5751.0

要将数据推送到dynamodb表,我需要JSON采用List<Map<String,Object>>格式的形式。

json数据如下所示:

{"dataset":{"id":19701916,"column_names":["Date","Cash Buyer","Cash Seller \u0026 Settlement","3-months Buyer","3-months Seller","15-months Buyer","15-months Seller","Dec 1 Buyer","Dec 1 Seller","Dec 2 Buyer","Dec 2 Seller","Dec 3 Buyer","Dec 3 Seller"],"frequency":"daily","type":"Time Series","premium":false,"limit":null,"transform":null,"column_index":null,"start_date":"2012-01-03","end_date":"2017-06-14","data":[["2017-06-14",5684.0,5684.5,5715.0,5717.0,null,null,5780.0,5790.0,5790.0,5800.0,5790.0,5800.0],["2017-06-13",5658.0,5659.0,5692.0,5693.0,null,null,5750.0,5760.0,5765.0,5775.0,5760.0,5770.0],["2017-06-12",5751.0,5752.0,5782.0,5783.0,null,null,5835.0,5845.0,5850.0,5860.0,5845.0,5855.0]"database_id":13206}}

此JSON数据在一个列表中具有列名,在另一个Array List中具有相应的值。我从API获取此JSON数据。 有人可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

首先,json无效(您可以对其进行验证here)。验证后,您可以使用任何Json序列化工具来读取和转换它。以下是杰克逊的一个例子(文档here):

//Deserialisation
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> dataMap = (Map<String, Object>) mapper.readValue("{\"dataset\":{\"id\":19701916,\"column_names\":[\"Date\",\"Cash Buyer\",\"Cash Seller Settlement\",\"3-months Buyer\",\"3-months Seller\",\"15-months Buyer\",\"15-months Seller\",\"Dec 1 Buyer\",\"Dec 1 Seller\",\"Dec 2 Buyer\",\"Dec 2 Seller\",\"Dec 3 Buyer\",\"Dec 3 Seller\"],\"frequency\":\"daily\",\"type\":\"Time Series\",\"premium\":false,\"limit\":null,\"transform\":null,\"column_index\":null,\"start_date\":\"2012-01-03\",\"end_date\":\"2017-06-14\",\"data\":[[\"2017-06-14\",5684.0,5684.5,5715.0,5717.0,null,null,5780.0,5790.0,5790.0,5800.0,5790.0,5800.0],[\"2017-06-13\",5658.0,5659.0,5692.0,5693.0,null,null,5750.0,5760.0,5765.0,5775.0,5760.0,5770.0],[\"2017-06-12\",5751.0,5752.0,5782.0,5783.0,null,null,5835.0,5845.0,5850.0,5860.0,5845.0,5855.0]]}}", Map.class);
System.out.println(transform((Map<String, Object>)dataMap.get("dataset")));


//Transformation

private static List<Map<String,Object>> transform (Map<String, Object> dataMap){
    List<Map<String,Object>> result = new ArrayList<>();
    List<String> columns = (List<String>) dataMap.get("column_names");
    List<List<Object>> data = (List<List<Object>>) dataMap.get("data");

    for(List<Object> dataElement : data){
        Map<String, Object> element = new HashMap<>();
        for(int i = 0 ; i < dataElement.size() ; i++){
            element.put(columns.get(i), dataElement.get(i));
        }
        result.add(element);
    }

    return result;
}

P.S。这只是使用MapList的示例。你可以创建Pojos并使用它们来摆脱施法。