简体   繁体   English

使用Google GSON将String转换为JSON数组

[英]Using Google GSON to convert String to JSON Array

I am using the Google GSON library to convert an ArrayList of countries into JSON: 我正在使用Google GSON库将国家/地区的ArrayList转换为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? 如何修改代码以生成JSON数组? 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. 这是Java客户端用来解析已经包含花括号的Web服务响应的代码。 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)));
    }

To build the string you show us, which isn't JSON at all, you may do this : 要构建您显示给我们的字符串(根本不是JSON),您可以执行以下操作:

StringBuilder sb = new StringBuilder("[{");
for (int i=0; i<countries.size(); i++) {
    sb.append("\"").append(countries.get(i)).append("\"");
    if (i<countries.size()-1) sb.append(",");
}
sb.append("}]");
String theString = sb.toString();

I'd recommend not trying to use Gson, which is only dedicated to JSON. 我建议不要尝试使用仅用于JSON的Gson。

A simple text-representation of an array in JSON is exactly what Gson returns. Gson返回的就是JSON中数组的简单文本表示形式。 What for do you need that curly-braces style? 您需要那种花括号样式吗?

Using curly-braces is not a "style", it is how JSON denotes an object. 使用花括号不是“样式”,而是JSON表示对象的方式。 square brackets represent a list, and curly-braces are used to represent an object, which in Javascript behaves like a map. 方括号表示列表,大括号表示对象,在Javascript中其行为类似于地图。 Putting curly braces around the list entries is nonsensical because within the object you need name-value pairs (just like a map). 将花括号放在列表条目周围是没有意义的,因为在对象内需要名称/值对(就像地图一样)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM