json看起来像这样:
"hour_totals": {
"382423": {
"imp": 126,
"clk": 1,
"spend": "$0.03",
"conv": 0,
"cpm": "$0.22",
"cpc": "$0.03",
"ctr": "0.79%",
"cpa": "$Inf"
},
"382424": {
"imp": 209,
"clk": 1,
"spend": "$0.05",
"conv": 0,
"cpm": "$0.23",
"cpc": "$0.05",
"ctr": "0.48%",
"cpa": "$Inf"
}}
我阅读了20多个答案,但无法找到如何反序列化这样的结构,请帮助该类看起来像什么,因为小时不是一个固定的字符串。
答案 0 :(得分:1)
要使用Gson解析此JSON,您需要两个步骤。
定义此类:
public class Total {
Map<String, HourData> hour_totals;
@Override
public String toString() {
return "Total [hour_totals=" + hour_totals + "]";
}
}
其中HourData
是
public class HourData {
Integer imp;
Integer clk;
String spend;
Integer conv;
String cpm;
String cpc;
String cpa;
@Override
public String toString() {
return "HourData [imp=" + imp + ", clk=" + clk + ", spend=" + spend
+ ", conv=" + conv + ", cpm=" + cpm + ", cpc=" + cpc + ", cpa="
+ cpa + "]";
}
}
哈哈一点你的“Json字符串”,因为它不是一个有效的Json(见下面的更多细节)。你只需要像这段代码一样添加大括号:
public class Q19201300 {
public static void main(String[] args) {
String json = "\"hour_totals\": { "
+ " \"382423\": { "
+ " \"imp\": 126, "
+ " \"clk\": 1, "
+ " \"spend\": \"$0.03\", "
+ " \"conv\": 0, "
+ " \"cpm\": \"$0.22\", "
+ " \"cpc\": \"$0.03\", "
+ " \"ctr\": \"0.79%\", "
+ " \"cpa\": \"$Inf\" "
+ "}, "
+ "\"382424\": { "
+ " \"imp\": 209, "
+ " \"clk\": 1, "
+ " \"spend\": \"$0.05\", "
+ " \"conv\": 0, "
+ " \"cpm\": \"$0.23\", "
+ " \"cpc\": \"$0.05\", "
+ " \"ctr\": \"0.48%\", "
+ " \"cpa\": \"$Inf\" "
+ "}} ";
Total t = new Gson().fromJson("{" + json + "}", Total.class);
System.out.println(t);
}
}
这会给你:
总计[hour_totals = {382423 = HourData [imp = 126,clk = 1,花费= $ 0.03, conv = 0,cpm = $ 0.22,cpc = $ 0.03,cpa = $ Inf],382424 = HourData [imp = 209, clk = 1,花费= $ 0.05,转换= 0,cpm = $ 0.23,cpc = $ 0.05,cpa = $ Inf]}]
关于你的字符串。来自JSON官方语法(http://www.ietf.org/rfc/rfc4627.txt):
- 醇>
JSON语法
JSON文本是一系列令牌。这组令牌包括 六个结构字符,字符串,数字和三个字面值 名。
JSON文本是序列化对象或数组。