【发布时间】:2013-06-04 12:27:39
【问题描述】:
我正在使用 Gson 解析 json 响应,但是我有一些关键字段可能会更改 像这样
{
"id_item": "5248549",
"id_unit": "10865300490",
"available_quantity": "8",
"title_item": "Casio G-Shock Bluetooth Connected Watch [GB-6900AB-1]",
"is_wow_deal": "0",
"img": "http://cf4.souqcdn.com/item/52/48/54/9/item_L_20130603124218_5248549.jpg",
"additional_attributes": {
"Brand": "Casio",
"Watch Shape": "Round",
"Band Material": "Resin",
"Display Type": "Digital",
"Targeted Group": "Men",
"Type": "Casual Watch"
},
"price": "539.00 AED"
}, {
"id_item": "5124140",
"id_unit": "19807600033",
"available_quantity": "18",
"title_item": "BlackBerry Q10 [English/Black]",
"is_wow_deal": "0",
"img": "http://cf4.souqcdn.com/item/51/24/14/0/item_L_20130604111349_5124140.jpg",
"additional_attributes": {
"Brand": "BlackBerry",
"Operating System": "BlackBerry OS"
},
"price": "2,269.00 AED"
},
additional_attributes 类可能会发生变化我正在尝试将其映射到 Hashmap,以便我可以对每个循环进行迭代;我可以进行手动解析和循环字符串响应。
下面是我打算实现的java程序,但是方法是错误的,欢迎提出任何建议。
public class test {
public static void main(String stringagr[]) {
String abc = "{ \"additional_attributes\": {\"Brand\": \"Samsung\",\"Operating System\": \"Android\",\"Storage Capacity\": \"8 GB\"}}";
Gson gson = new Gson();
attributes hashMap = gson.fromJson(abc, Attributes.class);
for (String string : hashMap.getAdditional_attributes().keySet()) {
if (string.length() > 0) {
}
}
}
class Attributes {
HashMap<String, String> additional_attributes;
public HashMap<String, String> getAdditional_attributes() {
return additional_attributes;
}
public void setAdditional_attributes(HashMap<String, String> additional_attributes) {
this.additional_attributes = additional_attributes;
}
}}
我也经历过以下方法
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class test {
public static void main(String stringagr[]) {
String abc = "{ \"additional_attributes\": {\"Brand\": \"Samsung\",\"Operating System\": \"Android\",\"Storage Capacity\": \"8 GB\"}}";
Gson gson = new Gson();
Type fooType = new TypeToken<Map<String, String>>() {
}.getType();
Map<String, String> map = gson.fromJson(abc, fooType);
for (String string : map.keySet()) {
if (string.length() > 0) {
}
}
}}
【问题讨论】:
-
attributes,test类名以小写字母开头,类名以大写字母开头。 -
@vipin sahu 看起来 souq.com 正在那里推出应用程序:D
-
是的,他们很快就会推出它