littleK
littleK

Reputation: 20133

Using Google GSON to convert String to JSON Array

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

Upvotes: 1

Views: 10388

Answers (3)

Nathan Hughes
Nathan Hughes

Reputation: 96395

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

Upvotes: 1

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

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.

Upvotes: 3

Javali
Javali

Reputation: 594

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

Upvotes: 1

Related Questions