I download the following JSON using the Wikipedia-Api:
["aa",
["Aarhus","Aalen","Aalborg","Aargau","Aare"],
["","","","",""],
["https://wiki.openstreetmap.org/wiki/Aarhus",
"https://wiki.openstreetmap.org/wiki/Aalen",
"https://wiki.openstreetmap.org/wiki/Aalborg",
"https://wiki.openstreetmap.org/wiki/Aargau",
"https://wiki.openstreetmap.org/wiki/Aare"
]
]
Several online JSON validators accept this format without warning or even errors.
This JSON is rejected by my program:
class OsmWikiResult {
private String start;
private String[] file;
private String[] dummy;
private String[] link;
}
... snip ...
Gson gson = new Gson();
OsmWikiResult owr = gson.fromJson(inputLine, OsmWikiResult.class);
inputLine is containing the whole JSON in one line.
java -jar target/OsmWiki-1.0-jar-with-dependencies.jar xxxx
OsmWiki
getListFromOsmWiki() starting.
Url: https://wiki.openstreetmap.org/w/api.php?action=opensearch&search=aa&limit=500&namespace=0&format=json
["aa",["Aarhus","Aalen","Aalborg","Aargau","Aare"],["","","","",""],["https://wiki.openstreetmap.org/wiki/Aarhus","https://wiki.openstreetmap.org/wiki/Aalen","https://wiki.openstreetmap.org/wiki/Aalborg","https://wiki.openstreetmap.org/wiki/Aargau","https://wiki.openstreetmap.org/wiki/Aare"]]
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:224)
at com.google.gson.Gson.fromJson(Gson.java:888)
at com.google.gson.Gson.fromJson(Gson.java:853)
at com.google.gson.Gson.fromJson(Gson.java:802)
at com.google.gson.Gson.fromJson(Gson.java:774)
at com.wno.OsmWiki.getListFromOsmWiki(OsmWiki.java:80)
at com.wno.OsmWiki.main(OsmWiki.java:114)
Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $
at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:385)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:213)
... 6 more
walter
The issue here is that you're attempting to parse an array into an object with keys start, file, dummy and link. You need to parse the root array into a JsonArray, then get the individual elements from that.
In its simplest form, something like this will work:
JsonArray root = parser.parse(inputLine).getAsJsonArray();
String searchedTerm = root.get(0).getAsString();
String[] resultTitles = gson.fromJson(root.get(1), String[].class);
String[] dummy = gson.fromJson(root.get(2), String[].class);
String[] links = gson.fromJson(root.get(3), String[].class);
I would suggest creating a custom JsonDeserializer or TypeAdapter to be able to just gson.fromJson() the whole shebang. Since your JSON doesn't have very deep nesting, I think you'll be able to get way with just implementing a JsonDeserializer. Just be aware that if you start running into performance issues, you might want to implement a TypeAdapter. Read more about their differences here.
Try this one out:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
public class Main {
public static void main(String[] args) {
String inputLine = "[\"aa\",[\"Aarhus\",\"Aalen\",\"Aalborg\",\"Aargau\",\"Aare\"],[\"\",\"\",\"\",\"\",\"\"],[\"https://wiki.openstreetmap.org/wiki/Aarhus\",\"https://wiki.openstreetmap.org/wiki/Aalen\",\"https://wiki.openstreetmap.org/wiki/Aalborg\",\"https://wiki.openstreetmap.org/wiki/Aargau\",\"https://wiki.openstreetmap.org/wiki/Aare\"]]";
Gson gson = new GsonBuilder()
.registerTypeAdapter(OsmWikiResult.class, new WikiSearchResultDeserializer())
.create();
OsmWikiResult result = gson.fromJson(inputLine, OsmWikiResult.class);
System.out.println("result.getSearchTerm() = " + result.getSearchTerm());
System.out.println("result.getResults() = " + String.join(", ", result.getResults()));
System.out.println("result.getLinks() = " + String.join(", ", result.getLinks()));
}
}
class WikiSearchResultDeserializer implements JsonDeserializer<OsmWikiResult> {
#Override
public OsmWikiResult deserialize(
JsonElement json,
Type typeOfT,
JsonDeserializationContext context
) throws JsonParseException {
JsonArray root = json.getAsJsonArray();
String searchTerm = root.get(0).getAsString();
String[] results = context.deserialize(root.get(1), String[].class);
String[] dummy = context.deserialize(root.get(2), String[].class);
String[] links = context.deserialize(root.get(3), String[].class);
return new OsmWikiResult(searchTerm, results, dummy, links);
}
}
class OsmWikiResult {
private String searchTerm;
private String[] results;
private String[] dummy;
private String[] links;
public OsmWikiResult(String searchTerm, String[] results, String[] dummy, String[] links) {
this.searchTerm = searchTerm;
this.results = results;
this.dummy = dummy;
this.links = links;
}
public String getSearchTerm() { return searchTerm; }
public String[] getResults() { return results; }
public String[] getDummy() { return dummy; }
public String[] getLinks() { return links; }
}
Notice how you need to register the deserializer with Gson so that it knows what to do when parsing an OsmWikiResult. The deserializer just plucks out the array's elements in correct order from the API result's array.
Related
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?
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 : 4
List 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.8
8.8.4.4
156.154.70.1
156.154.71.1
I was able to get the list mapping to work with just using #SerializedName for all fields.. no logic around Type 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 data
Here's an example:
1. The JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
public class FocusArea {
#SerializedName("name")
private String mName;
#SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
public class ContentImage {
#SerializedName("description")
private String mDescription;
#SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
Kotlin Extension
for Kotlin developers you can use this extension
inline fun <reified T> String.convertToListObject(): List<T>? {
val listType: Type = object : TypeToken<List<T?>?>() {}.type
return Gson().fromJson<List<T>>(this, listType)
}
Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.
So I have an object with some fields...
protected String name;
protected String relativePathAndFileName;
protected DateTime next_Run;
protected ArrayList<String> hosts;
Which gets serialized to JSON like this:
public void serialize(){
Gson gson = Converters.registerDateTime(new GsonBuilder()).setPrettyPrinting().create();
String json = gson.toJson(this);
try {
FileWriter writer = new FileWriter(this.relativePathAndFileName);
writer.write (json);
writer.close();
} catch (IOException e) {
logger.error("Error while trying to write myAlert to json: ", e);
}
}
Later when I need to read in this json file, I try to do so like this:
try {
for (File f : alertConfigFiles) {
Gson gson = new Gson();
JsonReader reader = new JsonReader(new FileReader(f));
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(reader, type);
Alert tempAlert = new Alert(myMap);
myAlerts.add(tempAlert);
logger.debug("Imported: " + f.toString());
}
The error that I'm getting is:
Unhandled exception when trying to import config files:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_ARRAY at line 28 column 13 path $.
The JSON inside the file is something to the effect of:
{
"name": "Logs Per Host - past 24 hours",
"relativePathAndFileName": "./Elk-Reporting/Alerts/logs_per_host24h.json",
"next_Run": "2017-06-07T22:24:56.682-04:00",
"hosts": [
"app-12c",
"app1-18",
"wp-01",
"app-02",
"wp-02",
"cent-04",
"app-06",
"app-05"
]
}
It seems to be choking when it tries to import the ArrayList of hosts, but it was able to write them out without issues.
Can anyone offer some advice on how to get my import working without issues?
try to keep it simple. Using maps and so on, is a way to have issues.
Here is a working code to deserialise / serialise :
package com.rizze.beans.labs.sof;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import com.google.gson.Gson;
public class SOFGson {
public String json = "{ \"name\": \"Logs Per Host - past 24 hours\", \"relativePathAndFileName\": \"./Elk-Reporting/Alerts/logs_per_host24h.json\", \"next_Run\": \"2017-06-07T22:24:56.682-04:00\", \"hosts\": [ \"bos-qa-app-12c\", \"bos-qa-app1-18\", \"bos-qa-wp-01\", \"bos-lt-app-02\", \"bos-qa-wp-02\", \"bos-dev-cent-04.americanwell.com\", \"bos-qa-app-06\", \"bos-qa-app-05\" ]}";
public class MyObj{
protected String name;
protected String relativePathAndFileName;
protected String next_Run;
protected String[] hosts;
}
#Test
public void test() {
Gson gson = new Gson();
MyObj obj = gson.fromJson(json, MyObj.class);
assertTrue(obj!=null);
assertTrue(obj.hosts.length==8);
System.out.println(gson.toJson(obj));
}
}
here is the class in gist : https://gist.github.com/jeorfevre/7b32a96d4ddc4af68e40bf95f63f2c26
Those two lines seem to be the problem:
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(reader, type);
You serialize your object of some specific class. You then deserialize it to type. But your JSON does not fit into a Map. Better do it like this, so you can use your own class.
YourClass myMap = gson.fromJson(reader, YourClass.class);
If you want to use this approach, you might want to change your Java class to hold an array of strings instead of an ArrayList of strings.
Maybe this page helps you a bit. Especially the first case fits your situation.
Another option is a custom Deserialzer as described here.
I have a JSON REST endpoint response and I wanted to get the value of hotelNbr from it. How do i do it ?
{
"found": [
{
"hotelNbr": 554050442,
"hotelAddress": "119 Maven Lane, New Jersey",
}
],
"errors": []
}
I am using the below code to get it but it fails in below mentioned line:
public List<Hotel> RDS_POST_HotelDetails(String HotelName, String sUrl) throws Exception, IOException {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
// Create your http client
CloseableHttpClient httpclient = HttpClientBuilder.create().build();
// Create http Put object
HttpPost ohttppost = new HttpPost(sUrl);
// Message Body
StringEntity input = new StringEntity(
"{\"hotelNbr\":[\""+HotelName+"\" ]}"
);
// Set content type for post
input.setContentType("application/json");
// attach message body to request
ohttppost.setEntity(input);
// submit request and save response
HttpResponse response = httpclient.execute(ohttppost);
// Get response body (entity and parse to string
String sEntity = EntityUtils.toString(response.getEntity());
List<Hotel> hotelobject = new ArrayList<Hotel>();
// Create a type token representing the type of objects in your json response
// I had to use the full class path of TYPE because we also have a Type class in our project
java.lang.reflect.Type cType = new TypeToken<List<Hotel>>() {
}.getType();
// Convert to Array object using gson.fromJson(<json string>,
// <type>)
hotelObject = gson.fromJson(sEntity, cType); // I am getting error here
String hotelNumber = hotelObject.get(0).getFound().get(0).getItemNbr().toString();
}
Please find the Hotel.java class below
package com.hotels.company;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Hotel {
#SerializedName("found")
#Expose
private List<Found> found = null;
#SerializedName("errors")
#Expose
private List<Object> errors = null;
public List<Found> getFound() {
return found;
}
public void setFound(List<Found> found) {
this.found = found;
}
public List<Object> getErrors() {
return errors;
}
public void setErrors(List<Object> errors) {
this.errors = errors;
}
}
Please find Found.java class below :
package com.hotels.company;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Found {
#SerializedName("hotelNbr")
#Expose
private Integer hotelNbr;
#SerializedName("hotelAddress")
#Expose
private String hotelAddress;
public Integer getHotelNbr() {
return hotelNbr;
}
public void setHotelNbr(Integer hotelNbr) {
this.hotelNbr = hotelNbr;
}
public String getHotelAddress() {
return hotelAddress;
}
public void setHotelAddress(String hotelAddress) {
this.hotelAddress = hotelAddress;
}
}
I tried finding some examples in StackOverflow questions but didn't get solution for mine. Any help will be appreciated.
The JSON you are parsing is not well formatted..
There is a comma after "hotelAddress" remove that
Correct JSON would be:
{
"found":[
{
"hotelNbr":554050442,
"hotelAddress":"119 Maven Lane, New Jersey"
}
],
"errors":[ ]
}
I found a couple of issues:
Json is not valid. Observe there is a comma at the end of "hotelAddress": "119 Maven Lane, New Jersey",. Remove it.
You are trying to deserialize the json into List<Hotel>, but the json mentioned is not a list. Either update the json or deserialise it into Hotel object instead of List.
I am strugling with my first Ckan application and from the reading i did i choose to use Gson. From Ckan, for testing, i try to get the user list by http://192.168.1.2:5000/api/action/user_list
This gives me
{"help":"http://192.168.1.2:5000/api/3/action/help_show?name=user_list",
"success":true,
"result":[
{ "openid":null,
"about":null,
"display_name":"default",
"name":"default",
"created":"2015-06-09T22:17:22.228196",
"email_hash":"d41d8cd98f00b204e9800998ecf8427e",
"sysadmin":true,
"activity_streams_email_notifications":false,
"state":"active",
"number_of_edits":0,
"fullname":null,
"id":"d5e49a3d-599d-49f3-9e20-826a03540357",
"number_created_packages":0
}, (..more data here...deleted for convenience)
{ "openid":null,
"about":null,
"display_name":"visitor",
"name":"visitor",
"created":"2015-06-09T22:16:52.785325",
"email_hash":"d41d8cd98f00b204e9800998ecf8427e",
"sysadmin":false,
"activity_streams_email_notifications":false,
"state":"active",
"number_of_edits":0,
"fullname":null,
"id":"9d279d8a-c068-46a5-9516-ed9c8de2f13b",
"number_created_packages":0
}
]
}
My problem is how to read this using Java.
What I did was
class JsonUserReply{
public String help;
public boolean success;
public JsonUsers[] userArray;
JsonUserReply(){}
}
class JsonUsers{
public String openid;
public String about;
public String display_name;
public String name;
public String created;
public String email_hash;
public boolean sysadmin;
public boolean act_email_notif;//"activity_streams_email_notifications"
public String state;
public int edits;
public String fullname;
public String id;
public int numb_cre_packs;//"number_created_packages"
JsonUsers(){}
}
I use the first class because the data provided is "some data, {array of Objects}".
Folowing some tutorials i used this:
Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<JsonUserReply>>(){}.getType();
Collection<JsonUserReply> enums = gson.fromJson(host, collectionType);
This gives me an error on the fromJson command of:
Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $
and the same error i get using this
JsonUserReply myTypes = gson.fromJson(host,JsonUserReply.class);
Edit
JsonUserReply myTypes = gson.fromJson(host,JsonUserReply.class);
throws Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $
while digging around i found and used this*
url = new URL(host); //("https://graph.facebook.com/search?q=java&type=post");
InputStream is = url.openStream();
JsonParser parser = Json.createParser(is);
while (parser.hasNext()) {
Event e = parser.next();
if (e == Event.KEY_NAME) {
switch (parser.getString()) {
case "name":
parser.next();
System.out.println("Name "+parser.getString());
break;
case "result":
System.out.println("RESULT1 "+parser.getString());
e=parser.next();
System.out.println("RESULT2 "+e.toString());
break;
default:
System.out.println(parser.getString());
break;
}
}
which even if it is way too complicated to use for my data as they are, it revieled something intresting. inside the case "result": i re-read the parser just to check whats its value. And it turns out that
RESULT1 result
RESULT2 START_ARRAY
RESULT3 START_OBJECT
To me that means that the json object is sending the data with the keyword"START_ARRAY" but Gson is expecting BEGIN_ARRAY. Am i right? apparently these two are not the same. how can i use the Gson way to get the array from my data? Thanks
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?
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 : 4
List 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.8
8.8.4.4
156.154.70.1
156.154.71.1
I was able to get the list mapping to work with just using #SerializedName for all fields.. no logic around Type 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 data
Here's an example:
1. The JSON
{
"name": "Some House",
"gallery": [
{
"description": "Nice 300sqft. den.jpg",
"photo_url": "image/den.jpg"
},
{
"description": "Floor Plan",
"photo_url": "image/floor_plan.jpg"
}
]
}
2. Java class with the List
public class FocusArea {
#SerializedName("name")
private String mName;
#SerializedName("gallery")
private List<ContentImage> mGalleryImages;
}
3. Java class for the List items
public class ContentImage {
#SerializedName("description")
private String mDescription;
#SerializedName("photo_url")
private String mPhotoUrl;
// getters/setters ..
}
4. The Java code that processes the JSON
for (String key : focusAreaKeys) {
JsonElement sectionElement = sectionsJsonObject.get(key);
FocusArea focusArea = gson.fromJson(sectionElement, FocusArea.class);
}
Kotlin Extension
for Kotlin developers you can use this extension
inline fun <reified T> String.convertToListObject(): List<T>? {
val listType: Type = object : TypeToken<List<T?>?>() {}.type
return Gson().fromJson<List<T>>(this, listType)
}
Given you start with mapping.get("servers").getAsJsonArray(), if you have access to Guava Streams, you can do the below one-liner:
List<String> servers = Streams.stream(jsonArray.iterator())
.map(je -> je.getAsString())
.collect(Collectors.toList());
Note StreamSupport won't be able to work on JsonElement type, so it is insufficient.