首先引用gson庫到程序中
也可以直接使用
compile 'com.google.code.gson:gson:2.8.0'
目前最新的蹦浦,請及時(shí)更新。撞蜂。盲镶。
好了不多說了,進(jìn)入正題
JsonObject object = (JsonObject) new JsonParser().parse(json);
JsonObject body = object.getAsJsonObject("Body");
這是將json數(shù)據(jù)直接轉(zhuǎn)換成有序的JsonObject谅摄,之前試了fastjson徒河,沒有找到解決無序的問題(水平比較有限??),嘗試用了gson送漠,果然還是gson比較好用??
到這里差不多就結(jié)束了顽照,由于服務(wù)器返回的json是不固定的所以,并且顯示時(shí)是key和value都需要的,所以代兵,我將body轉(zhuǎn)換成LinkedHashMap后在轉(zhuǎn)換成List尼酿,保證解析是有序的
String bodyJson = body.toString();
List<DetailEntity> list = new ArrayList<>();
Gson gson = new Gson();
LinkedHashMap<String, String> map = gson.fromJson(bodyJson, new TypeToken<LinkedHashMap<String, String>>() {
}.getType());
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = it.next();
if (!"".equals(entry.getValue())) {
Entity entity = new Entity();
entity.mKey = entry.getKey();
entity.mValue = entry.getValue();
list.add(entity);
}
}