且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Google GSON将字符串转换为JSON数组

更新时间:2022-10-21 23:13:17

一个样式,这是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).