如何生成所需的JSON / Java String结果

时间:2015-12-03 18:07:30

标签: java json

产品:

+-------------+--------------+-------+
| ProductCode |  OrderDate   | User  |
+-------------+--------------+-------+
|      100    | 2015-01-01   | John  |
|      100    | 2015-01-01   | Peter |
|      100    | 2015-01-02   | Max   |
|      200    | 2015-01-01   | Max   |
|      200    | 2015-01-05   | John  |
|      300    | 2015-01-10   | Peter |
+-------------+--------------+-------+

预期的JSON结构:

{
"100": {
    "2015-01-01": {
        "Jon": {
            "spent": "...",
            "comment": "..."
        },
        "Peter": {
            "spent": "...",
            "comment": "..."
        }
    },
    "2015-01-02": {
        "Max": {
            "spent": "...",
            "comment": "..."
        }
    }
},
"200": {
    "2015-01-01": {
        "Max": {
            "spent": "...",
            "comment": "..."
        }
    },
    "2015-01-05": {
        "Jon": {
            "spent": "...",
            "comment": "..."
        }
    }
},
"300": {
    "2015-01-10": {
        "Peter": {
            "spent": "...",
            "comment": "..."
        }
    }
}

}

到目前为止我做了什么:

//Create ListMultimap
ListMultimap<String, Product> productCodeMap = ArrayListMultimap.create();
ListMultimap<String, Product> productDateMap = ArrayListMultimap.create();
ListMultimap<String, Product> productUserMap = ArrayListMultimap.create();

//Fetch products
products  = dao.getProducts();

//Create map with relevant keys
for(Product product : products){
    productCodeMap.put(product.getProductCode(), product);
}
for(String productDate : productCodeMap.keySet()){
    for(Product product : productCodeMap.get(productDate)){
        productDateMap.put(product.getProductOrderDate(), product);
    }
}
for(String productUser : productDateMap.keySet()){
    for(Product product : productDateMap.get(productDate)){
        productUserMap.put(productUser, product);
    }
}

我应该如何迭代地图以生成所需的JSON结构?我应该使用不同的集合数据结构吗?

我正在使用Jackson Streaming API生成JSON。

即使您可以建议生成等效的JAVA字符串也会很棒,因为我正在做的是通过手动编写生成JSON。

0 个答案:

没有答案