Parsing JSON array into java.util.List with Gson
Definitely the easiest way to do that is using Gson's default parsing function fromJson()
.
There is an implementation of this function suitable for when you need to deserialize into any ParameterizedType
(e.g., any List
), which is fromJson(JsonElement json, Type typeOfT)
.
In your case, you just need to get the Type
of a List<String>
and then parse the JSON array into that Type
, like this:
import java.lang.reflect.Type;import com.google.gson.reflect.TypeToken;JsonElement yourJson = mapping.get("servers");Type listType = new TypeToken<List<String>>() {}.getType();List<String> yourList = new Gson().fromJson(yourJson, listType);
In your case yourJson
is a JsonElement
, but it could also be a String
, any Reader
or a JsonReader
.
You may want to take a look at Gson API documentation.
Below code is using com.google.gson.JsonArray
.I have printed the number of element in list as well as the elements in List
import java.util.ArrayList;import com.google.gson.Gson;import com.google.gson.JsonArray;import com.google.gson.JsonObject;import com.google.gson.JsonParser;public class Test { static String str = "{ "+ "\"client\":\"127.0.0.1\"," + "\"servers\":[" + " \"8.8.8.8\"," + " \"8.8.4.4\"," + " \"156.154.70.1\"," + " \"156.154.71.1\" " + " ]" + "}"; public static void main(String[] args) { // TODO Auto-generated method stub try { JsonParser jsonParser = new JsonParser(); JsonObject jo = (JsonObject)jsonParser.parse(str); JsonArray jsonArr = jo.getAsJsonArray("servers"); //jsonArr. Gson googleJson = new Gson(); ArrayList jsonObjList = googleJson.fromJson(jsonArr, ArrayList.class); System.out.println("List size is : "+jsonObjList.size()); System.out.println("List Elements are : "+jsonObjList.toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
OUTPUT
List size is : 4List Elements are : [8.8.8.8, 8.8.4.4, 156.154.70.1, 156.154.71.1]
I read solution from official website of Gson at here
And this code for you:
String json = "{"client":"127.0.0.1","servers":["8.8.8.8","8.8.4.4","156.154.70.1","156.154.71.1"]}"; JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); JsonArray jsonArray = jsonObject.getAsJsonArray("servers"); String[] arrName = new Gson().fromJson(jsonArray, String[].class); List<String> lstName = new ArrayList<>(); lstName = Arrays.asList(arrName); for (String str : lstName) { System.out.println(str); }
Result show on monitor:
8.8.8.88.8.4.4156.154.70.1156.154.71.1