我正在使用 Google GSON 库将国家/地区的 ArrayList 转换为 JSON:
ArrayList<String> countries = new ArrayList<String>();
// arraylist gts populated
Gson gson = new Gson();
String json = gson.toJson(countries);
产生:
["AFGHANISTAN","ALBANIA","ALGERIA","ANDORRA","ANGOLA","ANGUILLA","ANTARCTICA","ANTIGUA AND BARBUDA","ARGENTINA","ARMENIA","ARUBA","ASHMORE AND CARTIER ISLANDS","AUSTRALIA","AUSTRIA","AZERBAIJAN"]
如何修改我的代码以生成 JSON 数组?例如:
[
{
"AFGHANISTAN",
"ALBANIA",
"ALGERIA",
"ANDORRA",
"ANGOLA",
"ANGUILLA",
"ANTARCTICA",
"ANTIGUA AND BARBUDA",
"ARGENTINA",
"ARMENIA",
"ARUBA",
"ASHMORE AND CARTIER ISLANDS",
"AUSTRALIA",
"AUSTRIA",
"AZERBAIJAN"
}
]
谢谢!
这是我的 Java 客户端用来解析已经包含大括号的 Web 服务响应的代码。这就是为什么我希望国家/地区的响应包含花括号:
Gson gson = new GsonBuilder().create();
ArrayList<Map<String, String>> myList = gson.fromJson(result,
new TypeToken<ArrayList<HashMap<String, String>>>() {
}.getType());
List<Values> list = new ArrayList<Values>();
for (Map<String, String> m : myList) {
list.add(new Values(m.get(attribute)));
}