[英]Converting json string to map
我有一個json字符串,我的要求是隱秘進入map,其中key將是json的字段。 以下是我的json
{
"A":[
{
"B":[
{
"C":[
{
"D1":"V1",
"D2":"X1",
"D3":Y1,
"D4":"Z1"
},
{
"D1":"V2",
"D2":"X2",
"D3":Y2,
"D4":"Z2"
}
]
}
]
}
]
}
鍵應類似於“ A-> B-> C-> D1”和相應的值V1,V2。 地圖簽名應類似於Map<String,List<String>>
。 這里發布了類似的問題,但我的問題是在json字段之外創建密鑰。讓我知道是否需要更多信息。 提前致謝。
我做了一些可以回答您的確切結構的事情,在此我將D3的值也更改為字符串:
整個對象的Wraper
類
public class Wraper {
public Wraper() {}
@JsonProperty("A") A[] a;
}
A
級
public class A {
@JsonProperty("B") B[] b;
}
B
級
public class B {
@JsonProperty("C") C[] c;
}
C
級
public class C {
@JsonProperty("D1") String d1;
@JsonProperty("D2") String d2;
@JsonProperty("D3") String d3;
@JsonProperty("D4") String d4;
}
最后是我測試的地方:
static final String JSON_VAL="{\"A\":[{\"B\":[{\"C\":[{\"D1\":\"V1\",\"D2\":\"X1\",\"D3\":\"Y1\",\"D4\":\"Z1\"},{\"D1\":\"V2\",\"D2\":\"X2\",\"D3\":\"Y2\",\"D4\":\"Z2\"}]}]}]}";
final ObjectMapper mapper = new ObjectMapper();
final Wraper wraper = mapper.readValue(JSON_VAL, Wraper.class);
final Map<String,List<String>> map = new HashMap<>();
Arrays.stream(wraper.a).forEach(a -> {
Arrays.stream(a.b).forEach(b -> {
final List<String> d1 = new ArrayList<>();
final List<String> d2 = new ArrayList<>();
final List<String> d3 = new ArrayList<>();
final List<String> d4 = new ArrayList<>();
Arrays.stream(b.c).forEach(c -> {
d1.add(c.d1);
d2.add(c.d2);
d3.add(c.d3);
d4.add(c.d4);
});
map.put("A->B->C->D1", d1);
map.put("A->B->C->D2", d2);
map.put("A->B->C->D3", d3);
map.put("A->B->C->D4", d4);
});
});
使用正確的Java類定義(基於JSON)嘗試Jackson。
這是一些代碼:
public class topElement
{
private ElementA[] A;
public ElementA[] getA()
{
return A;
}
public void setA(
final ElementA[] newValue)
{
A = newValue;
}
}
public class ElementA
{
private ElementB[] B;
public ElementB[] getB()
{
return B;
}
public void setB(
final ElementB[] newValue)
{
B = newValue;
}
}
public class ElementB
{
private ElementC[] C;
public ElementC[] getC()
{
return C;
}
public void setC(
final ElementC[] newValue)
{
C = newValue;
}
}
public class ElementC
{
private Map blammyMap;
public Map getBlammyMap()
{
return blammyMap;
}
public void setBlammyMap(
final Map newValue)
{
blammyMap = newValue;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.