使用Google GSON将字符串转换为JSON数组 [英] Using Google GSON to convert String to JSON Array
问题描述
我使用Google GSON库将国家的ArrayList转换为JSON:
ArrayList< String> countries = new ArrayList< String>();
// arraylist gts已填充
Gson gson = new Gson();
String json = gson.toJson(countries);
其中:
阿富汗阿尔巴尼亚阿尔及利亚安道尔安哥拉安圭拉南极洲安提瓜和巴布达阿根廷亚美尼亚 ARUBA,ASHMORE和CARTIER ISLANDS,AUSTRALIA,AUSTRIA,AZERBAIJAN]
如何修改我的代码以生成JSON数组?例如:
[
{
AFGHANISTAN,
ALBANIA,
ALGERIA,
ANDORRA,
ANGOLA,
ANGUILLA,
ANTARCTICA,
ANTIGUA和BARBUDA,
阿根廷,
亚美尼亚,
阿鲁巴,
阿什哈尔和卡地亚群岛,
澳大利亚,
奥地利,
AZERBAIJAN
}
]
谢谢! p>
以下是我的Java客户端用于解析已包含花括号的Web服务响应的代码。这就是为什么我希望国家响应包含大括号:
Gson gson = new GsonBuilder()。create();
ArrayList< Map< String,String>> myList = gson.fromJson(result,
new TypeToken< ArrayList< HashMap< String,String>>>(){
} .getType());
列出<值> list = new ArrayList< Values>(); (Map< String,String> m:myList){
list.add(new Values(m.get(attribute)));
一个样式,这是JSON如何表示一个对象。方括号表示一个列表,用花括号表示一个对象,在Javascript中的行为就像一张地图。在列表条目周围放置大括号是无意义的,因为在对象内您需要名称 - 值对(就像地图一样)。
I am using the Google GSON library to convert an ArrayList of countries into JSON:
ArrayList<String> countries = new ArrayList<String>();
// arraylist gts populated
Gson gson = new Gson();
String json = gson.toJson(countries);
Which yields:
["AFGHANISTAN","ALBANIA","ALGERIA","ANDORRA","ANGOLA","ANGUILLA","ANTARCTICA","ANTIGUA AND BARBUDA","ARGENTINA","ARMENIA","ARUBA","ASHMORE AND CARTIER ISLANDS","AUSTRALIA","AUSTRIA","AZERBAIJAN"]
How can I modify my code to generate a JSON Array? For example:
[
{
"AFGHANISTAN",
"ALBANIA",
"ALGERIA",
"ANDORRA",
"ANGOLA",
"ANGUILLA",
"ANTARCTICA",
"ANTIGUA AND BARBUDA",
"ARGENTINA",
"ARMENIA",
"ARUBA",
"ASHMORE AND CARTIER ISLANDS",
"AUSTRALIA",
"AUSTRIA",
"AZERBAIJAN"
}
]
Thanks!
Here is the code that my Java client uses to parse web service responses that already contain the curly-braces. This is why I want the countries response to contain the curly braces:
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)));
}
Using curly-braces is not a "style", it is how JSON denotes an object. square brackets represent a list, and curly-braces are used to represent an object, which in Javascript behaves like a map. Putting curly braces around the list entries is nonsensical because within the object you need name-value pairs (just like a map).
这篇关于使用Google GSON将字符串转换为JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!