Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson Array of Strings to JsonArray

Tags:

java

json

gson

I'm using Gson and am trying to add a bunch of string values into a JsonArray like this:

JsonArray jArray = new JsonArray(); jArray.add("value1"); 

The problem is that the add method only takes a JsonElement.

I've tried to cast a String into a JsonElement but that didn't work.

How do I do it using Gson?

like image 330
RedEagle Avatar asked May 08 '12 11:05

RedEagle


People also ask

How to convert Array list to JSONArray?

We can convert a list to the JSON array using the JSONArray. toJSONString() method and it is a static method of JSONArray, it will convert a list to JSON text and the result is a JSON array.

How to convert JSON array to list in Java using Gson?

TypeToken; JsonElement yourJson = mapping. get("servers"); Type listType = new TypeToken<List<String>>() {}. getType(); List<String> yourList = new Gson().

How to get JSON array from JSON object in Java using Gson?

JSON array of {object with an array of object}.Type listType = new TypeToken<List<Item>>() {}. getType(); List<Item> list = gson. fromJson(main. loadFileFromClasspath("array2.


2 Answers

You can create a primitive that will contain the String value and add it to the array:

JsonArray jArray = new JsonArray(); JsonPrimitive element = new JsonPrimitive("value1"); jArray.add(element); 
like image 183
alexey28 Avatar answered Oct 02 '22 12:10

alexey28


Seems like you should make a new JsonPrimitive("value1") and add that. See The javadoc

like image 32
slipset Avatar answered Oct 02 '22 10:10

slipset