我有以下JSON我需要能够在POJO中呈现,我怎么能 这样做?
JSON每天有一个密钥,每个密钥的值是两个独立的逻辑阵列,我使用的是Jackson库。
{
"2014/01/02": [
{"ABC": 2.25, "XYZ": 4.05},
{"amazon.com": 3}
],
"2014/01/03": [
{"ABC": 13.02},
{"amazon.com": 3}
]
}
答案 0 :(得分:2)
你没有太多选择。这是一个丑陋的JSON。没有一致的格式,您可以在其中创建POJO。
您需要考虑的事项。这个{}
是一个JSON对象。我是Java映射术语,它可以映射到POJO,也可以映射到Map
。为了映射到POJO,您需要常见的属性名称和格式,而您似乎并不喜欢它们。这一切似乎都在变化。因此,您可能需要使用Map
。这是我看待它的方式
{ // Start Map
"2014/01/02": [ // Map key: start Array ( List<Map> )
{"ABC": 2.25, "XYZ": 4.05}, // Start another Map
{"amazon.com": 3} // another Map
您可以使用@JsonAnySetter
来简化,使用POJO包装器,但最终我仍然会在我的评论中指出Map<String, List<Map<String, Object>>
。如果你想要POJO,需要一些常见的格式。
以下是一种让它发挥作用的方法的例子
POJO
public class Dynamic {
private Map<String, Object> map = new HashMap<>();
public Object get(String key) {
return map.get(key);
}
public Map<String, Object> getMap() {
return map;
}
@JsonAnySetter
public void set(String name, Object value) {
map.put(name, value);
}
}
测试(在simple.json文件中使用您的确切JSON)
public class Test {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
Dynamic dynamic = mapper.readValue(new File("simple.json"), Dynamic.class);
for (String key : dynamic.getMap().keySet()) {
System.out.println("key: " + key);
System.out.println("--------");
List<Map<String, Object>> list = (List<Map<String, Object>>) dynamic.get(key);
for (Map<String, Object> map : list) {
for (Map.Entry<String, Object> entry: map.entrySet()) {
System.out.println("key: " + entry.getKey() + ", value: " + entry.getValue());
}
}
System.out.println("========");
}
}
}
结果
key: 2014/01/03
--------
key: ABC, value: 13.02
key: amazon.com, value: 3
========
key: 2014/01/02
--------
key: ABC, value: 2.25
key: XYZ, value: 4.05
key: amazon.com, value: 3
========
答案 1 :(得分:0)
{
"2014/01/02": [
{"ABC": 2.25, "XYZ": 4.05},
{}
],
"2014/01/03": [
{"ABC": 13.02},
{"amazon.com": 3}
]
}
This is even JSON, but not useful. I would make JSON for this like below.
{
[
{date: '2014/01/01',data:[{abc: 13.02, "amazonCom": 3},{abc: 13.02, "amazonCom": 3}},
{date: '2014/01/02',data:[{abc: 13.02, "amazonCom": 3},{abc: 13.02, "amazonCom": 3}},
]
}
Java
public jsonObj {
private String date;
private List<DateData> data;
.... setter//getter
}
public class DateData {
private double abc;
private int amazoneCom;
//constructor and getter/setter
}
You can use JSON libraries like below.
1. Jackson - http://jackson.codehaus.org/
2. Gson - https://code.google.com/p/google-gson/
Those libraries helps you to convert json into Java Object and vise versa as well.
Hope it can help you with solving your problem.
答案 2 :(得分:0)
There are many ways to transform json to pojo. Here I am sharing few URL to achieve the same