I have a JsonObject
named "mapping"
with the following content:
{
"client": "127.0.0.1",
"servers": [
"8.8.8.8",
"8.8.4.4",
"156.154.70.1",
"156.154.71.1"
]
}
I know I can get the array "servers"
with:
mapping.get("servers").getAsJsonArray()
And now I want to parse that JsonArray
into a java.util.List
...
What is the easiest way to do this?
I read solution from official website of Gson at here
And this code for you:
Result show on monitor:
Given you start with
mapping.get("servers").getAsJsonArray()
, if you have access to GuavaStreams
, you can do the below one-liner:Note
StreamSupport
won't be able to work onJsonElement
type, so it is insufficient.Below code is using
com.google.gson.JsonArray
. I have printed the number of element in list as well as the elements in ListOUTPUT
I was able to get the list mapping to work with just using
@SerializedName
for all fields.. no logic aroundType
was necessary.Running the code - in step #4 below - through the debugger, I am able to observe that the
List<ContentImage> mGalleryImages
object populated with the JSON dataHere's an example:
1. The JSON
2. Java class with the List
3. Java class for the List items
4. The Java code that processes the JSON
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., anyList
), which isfromJson(JsonElement json, Type typeOfT)
.In your case, you just need to get the
Type
of aList<String>
and then parse the JSON array into thatType
, like this:In your case
yourJson
is aJsonElement
, but it could also be aString
, anyReader
or aJsonReader
.You may want to take a look at Gson API documentation.