Using Google GSON to convert String to JSON Array

匿名 (未验证) 提交于 2019-12-03 09:52:54

问题:

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)));     } 

回答1:

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).



回答2:

To build the string you show us, which isn't JSON at all, you may do this :

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.



回答3:

A simple text-representation of an array in JSON is exactly what Gson returns. What for do you need that curly-braces style?



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!