How to Parse JSON Array with Gson - java

I want to parse JSON arrays and using gson. Firstly, I can log JSON output, server is responsing to client clearly.
Here is my JSON output:
[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
I tried this structure for parsing. A class, which depends on single array and ArrayList for all JSONArray.
public class PostEntity {
private ArrayList<Post> postList = new ArrayList<Post>();
public List<Post> getPostList() {
return postList;
}
public void setPostList(List<Post> postList) {
this.postList = (ArrayList<Post>)postList;
}
}
Post class:
public class Post {
private String id;
private String title;
/* getters & setters */
}
When I try to use gson no error, no warning and no log:
GsonBuilder gsonb = new GsonBuilder();
Gson gson = gsonb.create();
PostEntity postEnt;
JSONObject jsonObj = new JSONObject(jsonOutput);
postEnt = gson.fromJson(jsonObj.toString(), PostEntity.class);
Log.d("postLog", postEnt.getPostList().get(0).getId());
What's wrong, how can I solve?

You can parse the JSONArray directly, don't need to wrap your Post class with PostEntity one more time and don't need new JSONObject().toString() either:
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);

I was looking for a way to parse object arrays in a more generic way; here is my contribution:
CollectionDeserializer.java:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import com.google.gson.Gson;
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;
public class CollectionDeserializer implements JsonDeserializer<Collection<?>> {
#Override
public Collection<?> deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
Type realType = ((ParameterizedType)typeOfT).getActualTypeArguments()[0];
return parseAsArrayList(json, realType);
}
/**
* #param serializedData
* #param type
* #return
*/
#SuppressWarnings("unchecked")
public <T> ArrayList<T> parseAsArrayList(JsonElement json, T type) {
ArrayList<T> newArray = new ArrayList<T>();
Gson gson = new Gson();
JsonArray array= json.getAsJsonArray();
Iterator<JsonElement> iterator = array.iterator();
while(iterator.hasNext()){
JsonElement json2 = (JsonElement)iterator.next();
T object = (T) gson.fromJson(json2, (Class<?>)type);
newArray.add(object);
}
return newArray;
}
}
JSONParsingTest.java:
public class JSONParsingTest {
List<World> worlds;
#Test
public void grantThatDeserializerWorksAndParseObjectArrays(){
String worldAsString = "{\"worlds\": [" +
"{\"name\":\"name1\",\"id\":1}," +
"{\"name\":\"name2\",\"id\":2}," +
"{\"name\":\"name3\",\"id\":3}" +
"]}";
GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Collection.class, new CollectionDeserializer());
Gson gson = builder.create();
Object decoded = gson.fromJson((String)worldAsString, JSONParsingTest.class);
assertNotNull(decoded);
assertTrue(JSONParsingTest.class.isInstance(decoded));
JSONParsingTest decodedObject = (JSONParsingTest)decoded;
assertEquals(3, decodedObject.worlds.size());
assertEquals((Long)2L, decodedObject.worlds.get(1).getId());
}
}
World.java:
public class World {
private String name;
private Long id;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}

To conver in Object Array
Gson gson=new Gson();
ElementType [] refVar=gson.fromJson(jsonString,ElementType[].class);
To convert as post type
Gson gson=new Gson();
Post [] refVar=gson.fromJson(jsonString,Post[].class);
To read it as List of objects TypeToken can be used
List<Post> posts=(List<Post>)gson.fromJson(jsonString,
new TypeToken<List<Post>>(){}.getType());

Type listType = new TypeToken<List<Post>>() {}.getType();
List<Post> posts = new Gson().fromJson(jsonOutput.toString(), listType);

Some of the answers of this post are valid, but using TypeToken, the Gson library generates a Tree objects whit unreal types for your application.
To get it I had to read the array and convert one by one the objects inside the array. Of course this method is not the fastest and I don't recommend to use it if you have the array is too big, but it worked for me.
It is necessary to include the Json library in the project. If you are developing on Android, it is included:
/**
* Convert JSON string to a list of objects
* #param sJson String sJson to be converted
* #param tClass Class
* #return List<T> list of objects generated or null if there was an error
*/
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){
try{
Gson gson = new Gson();
List<T> listObjects = new ArrayList<>();
//read each object of array with Json library
JSONArray jsonArray = new JSONArray(sJson);
for(int i=0; i<jsonArray.length(); i++){
//get the object
JSONObject jsonObject = jsonArray.getJSONObject(i);
//get string of object from Json library to convert it to real object with Gson library
listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
}
//return list with all generated objects
return listObjects;
}catch(Exception e){
e.printStackTrace();
}
//error: return null
return null;
}

You can easily do this in Kotlin using the following code:
val fileData = "your_json_string"
val gson = GsonBuilder().create()
val packagesArray = gson.fromJson(fileData , Array<YourClass>::class.java).toList()
Basically, you only need to provide an Array of YourClass objects.

[
{
id : '1',
title: 'sample title',
....
},
{
id : '2',
title: 'sample title',
....
},
...
]
Check Easy code for this output
Gson gson=new GsonBuilder().create();
List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

in Kotlin :
val jsonArrayString = "['A','B','C']"
val gson = Gson()
val listType: Type = object : TypeToken<List<String?>?>() {}.getType()
val stringList : List<String> = gson.fromJson(
jsonArrayString,
listType)

you can get List value without using Type object.
EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));
I have tested it and it is working.

Related

How to generate Json with Java

I am working on an application where i have to generate a json like this:
[
{"title":"Culture","start":"Salary","end":"Work"},
{"title":"Work","start":"Salary","end":"Work"}
]
But my code generates json like this:
{{"name":"Culture"},[{"name":"Salary"},{"name":"Work"}],}
My code:
public class ParseJson {
public static class EntryListContainer {
public List<Entry> children = new ArrayList<Entry>();
public Entry name;
}
public static class Entry {
private String name;
public Entry(String name) {
this.name = name;
}
}
public static void main(String[] args) {
EntryListContainer elc1 = new EntryListContainer();
elc1.name = new Entry("Culture");
elc1.children.add(new Entry("Salary"));
elc1.children.add(new Entry("Work"));
ArrayList<EntryListContainer> al = new ArrayList<EntryListContainer>();
Gson g = new Gson();
al.add(elc1);
StringBuilder sb = new StringBuilder("{");
for (EntryListContainer elc : al) {
sb.append(g.toJson(elc.name));
sb.append(",");
sb.append(g.toJson(elc.children));
sb.append(",");
}
String partialJson = sb.toString();
if (al.size() > 1) {
int c = partialJson.lastIndexOf(",");
partialJson = partialJson.substring(0, c);
}
String finalJson = partialJson + "}";
System.out.println(finalJson);
}
}
Can anyone help me to generate this json in my required format ?? please thanks in advance
Try this
public class Entry {
public String title;
public String start;
public String end;
}
And in another part of your code
private ArrayList<Entry> entries = new ArrayList<>();
// Fill the entries...
String the_json = new Gson().toJson(entries);
1) First Create your POJO
public class MyJSONObject {
private String title;
private String start;
private String end;
//getter and setter methods
[...]
#Override
public String toString() {
}
}
2) Use com.google.code.gson library
public static void main(String[] args) {
{
ArrayList<MyJSONObject> myJSONArray = new ArrayList<>();
MyJSONObject obj = new MyJSONObject();
obj.setTitle="Culture";
obj.set[...]
myJSONArray.add(obj);
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(myJSONArray);
System.out.println(json);
}
Output : [{"title":"Culture","start":"Salary","end":"Work"}, ...]
I recommend you to use some JSON Java API, like Gson. It's very simple to generate a string json from a POJO object or to create a POJO object from a string json.
The code for generating a string json from a POJO object is like this:
Gson gson = new Gson();
String stringJson = gson.toJson(somePojoObject);
The code for creating a POJO object from a string json is like this:
Gson gson = new Gson();
SomePojoClass object = gson.fromJson(stringJson, SomePojoClass.class);
Note that you can not serialize objects with circular references. This causes infinite recursion.

How to extract array values within nested JSON data

I have JSON data in the following format:
{
"data": {
"id": 14810798216415,
"name": "crescentbahuman.com",
"is_organization": true,
"email_domains": [
"crescentbahuman.com"
]
}
}
I want to get the string in the "email_domains" field. I wrote the following code as my attempt:
JSONObject dataObject2= (JSONObject)jsonObject2.get("data");
long id = (long) dataObject2.get("id");
System.out.println("worksapce id is: " + id);
String name = (String) dataObject2.get("name");
System.out.println("The worksapce name is: " + name);
boolean is_organization = (boolean) dataObject2.get("is_organization");
System.out.println("The workspace is organization: " + is_organization);
JSONArray email_domains = (JSONArray) jsonObject2.get("email_domains");
Iterator<String> iterator = email_domains.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
In this code to get "email_domains" only, a JSON Array object is created that get data from the JSON object and then its iterator is used to get values from within the array. However, it throws a NullPointerException on this line:
Iterator<String> iterator = email_domains.iterator();
I am stuck due to this problem. Can anyone kindly suggest a solution?
If you are using the JSON library from http://www.json.org/java/, then you should not be using JSONObject.get() so frequently. The library has other methods to get specific types, such as getLong(), getJSONArray(), and so forth. For your case with the "email_domains" field, you should try:
JSONArray array = dataObject2.getJSONArray("email_domains");
String value = array.getString(0);
org.json.JSONArray email_domains = (org.json.JSONArray) json.get("email_domains");
int length = email_domains.length();
for(int i = length-1; i > 0; i--) {
org.json.JSONObject jsonData = (org.json.JSONObject) email_domains.get(i);
System.out.println(jsonData);
}
My solution? I hate to be someone to offer a solution in another library... but look into google collections and the Gson helper. It can turn your Json into a map for you, and then back to json again when you are done.
Map map = gson.fromJson(jsonText, Map.class);
JsonArray's can then be cast into List's
try this to fetch "email_domains"
JSONArray email_domains = ((JSONArray) jsonObject).get("email_domains");
or
JSONObject obj = new JSONObject(jsonObject.Tostring());
JSONArray email_domains = obj.optJSONArray("email_domains");
"email_address" is JSONArray so we need to fetch this like
JSONArray email_domains = (JSONArray) dataObject2.getJSONArray("email_domains");
email_domains.get(0); // this will return crescentbahuman.com
Use this implementation
import java.lang.reflect.Field;
import java.util.List;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonConvertor {
private static GsonBuilder gsonBuilder;
private static Gson gson;
private JsonConvertor() {
}
public static Object fromJson(String json, Class clz)
{
gson=new Gson();
return gson.fromJson(json,clz);
}
public static String toJson(Object obj) {
gsonBuilder = new GsonBuilder();
gsonBuilder = gsonBuilder
.addSerializationExclusionStrategy(new CustomIclusionStrategy(
obj.getClass()));
gson = gsonBuilder.create();
String json = gson.toJson(obj);
return json;
}
}
class CustomIclusionStrategy implements ExclusionStrategy {
private Class classToIclude;
private Field[] declaredFields;
private List<FieldAttributes> fields;
public CustomIclusionStrategy(List<FieldAttributes> fields) {
this.fields = fields;
}
public CustomIclusionStrategy(Class classToIclude) {
this.classToIclude = classToIclude;
this.declaredFields=classToIclude.getDeclaredFields();
}
// called only if shouldSkipClass returns false
#Override
public boolean shouldSkipField(FieldAttributes f) {
try {
classToIclude.getSuperclass().getDeclaredField(f.getName());
System.out.println(f.getName());
return true;
} catch (Exception e) {
}
return false;
}
#Override
public boolean shouldSkipClass(Class<?> clazz) {
// if returns false shouldSkipField will be called, otherwise
//shouldSkipField will not be called
return false;
}
}
public class Org {
private Data data;
public Org(Data data) {
super();
this.data = data;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
public String toJson()
{
return JsonConvertor.toJson(this);
}
public static void main(String[] args) {
String json="{\"data\": {\"id\":\"1\",\"name\":\"org1\",\"is_organization\":true,\"email_domains\": [\"email1\",\"email2\",\"email3\",\"email4\"]}}";
Org o=(Org) JsonConvertor.fromJson(json, Org.class);
System.out.println(o.getData().getEmail_domains());
}
}

How to convert Map of class<T> objects to json java

I have class with some properties, for example:
public class MyClass {
public int number;
public String s;
}
and I want to convert Map of this class to json. for example:
Map<String, MyClass> map = new HashMap();
map.put("sss", new MyClass(1, "blabla");
json j = new json(map);
and I want the output to be like:
{"sss":{"number":"1","s":"blabla"}}
someone know how to do that in JAVA? I tried with JSONObject and with Gson but did not work for me.
you can use toJson() method of Gson class to convert a java object to json ,see the example below ,
public class SomeObject {
private int data1 = 100;
private String data2 = "hello";
private List<String> list = new ArrayList<String>() {
{
add("String 1");
add("String 2");
add("String 3");
}
};
//getter and setter methods
#Override
public String toString() {
return "SomeObject [data1=" + data1 + ", data2=" + data2 + ", list="
+ list + "]";
}
}
i will convert the above class' object to json , getter and setter methods are useful when you are converting the json back to java object .
public static void main(String[] args) {
SomeObject obj = new SomeObject();
Gson gson = new Gson();
// convert java object to JSON format,
// and returned as JSON formatted string
String json = gson.toJson(obj);
System.out.println(json);
}
output :
{"data1":100,"data2":"hello","list":["String 1","String 2","String 3"]}
Using Gson:
Gson gson = new GsonBuilder().create();
String json = gson.toJson(map);
You have to fix, parenthesis issue.
map.put("sss", new MyClass(1,"test")); //observe 2 braces at the end!
Following code should do the trick for you,
Gson gson = new Gson();
String myJson = gson.toJson(map);
Output:
{"sss":{"number":1,"s":"test"}}
Implement some custom toJSON() method for each class as shown below:
public class MyClass1 {
String number;
String name;
public MyClass1(String number, String name){
this.number = number;
this.name = name;
}
public JSONObject toJSON() throws JSONException {
return new JSONObject("{\"number\" : \""+this.number+"\", \"name\":\""+this.name+"\"}");
}
}
And then just use it to convert your map to jsonObject:
public class MapToJSON {
public static void main(String[] args) throws JSONException {
Map<String, JSONObject> map = new HashMap<String, JSONObject>();
map.put("sss", new MyClass1("1", "Hello").toJSON());
System.out.println(new JSONObject(map));
}
}
I found the way how to do that:
import com.google.gson.Gson;
import org.json.JSONObject;
Gson gson = new Gson();
map.put("sss", new JSONObject(gson.toJson(new MyClass(1, "Hello"))));
map.put("aaa", new JSONObject(gson.toJson(new MyClass(2, "blabla"))));
String output = new JSONObject(map).toString();
and now the output is correct.
Thanks a lot to all the people that tried to help me with this problem...

Deserialize a JSON response with Gson containing a field of variable type

The responses of a REST API always return a JSON with the following structure:
{
"status": "<status_code>",
"data": <data_object>
}
My problem is that the value of data doesn't have an unique type, but it can be a String, a JSON Object or a JSON Array, depending on the called endpoint. I can't figure out how to deserialize it in the right way to create the different Java objects...
For example, I've already prepared some POJOs: the root element
public class ApiResult {
#SerializedName("status")
public String status;
#SerializedName("data")
public JsonElement data; // should I define it as a JsonElement??
}
and two objects that reflects two of the endpoints:
// "data" can be a list of NavItems
public class NavItem {
#SerializedName("id")
public String id;
#SerializedName("name")
public String name;
#SerializedName("icon")
public String icon;
#SuppressWarnings("serial")
public static class List extends ArrayList<NavItem> {}
}
and
// "data" can be a single object representing a Profile
public class Profile {
#SerializedName("id")
public String id;
#SerializedName("fullname")
public String fullname;
#SerializedName("avatar")
public String avatar;
}
Reading some StackOverflow questions, I've seen I should use the JsonDeserializer<T> interface. But how if the type of data in ApiResult is variable?
You should use a a custom JsonDeserializer and write all your logic there, like this
ApiResult.java
public class ApiResult {
#SerializedName("status")
public String status;
#SerializedName("data")
public Object data;
}
ApiResultDeserializer.java
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
public class ApiResultDeserializer implements JsonDeserializer<ApiResult> {
private Type listType = new TypeToken<List<NavItem>>(){}.getType();
#Override
public ApiResult deserialize(JsonElement value, Type type,
JsonDeserializationContext context) throws JsonParseException {
final JsonObject apiResultJson = value.getAsJsonObject();
final ApiResult result = new ApiResult();
result.status = apiResultJson.get("status").getAsString();
JsonElement dataJson = apiResultJson.get("data");
if(dataJson.isJsonObject()) {
result.data = context.deserialize(dataJson, NavItem.class);
} else if(dataJson.isJsonPrimitive()) {
result.data = context.deserialize(dataJson, String.class);
} else if(dataJson.isJsonArray()) {
result.data = context.deserialize(dataJson, listType);
}
return result;
}
}
and try to create different kinds of data (List, Object, or String) as you mentioned
Main.java
Gson gson = new GsonBuilder()
.registerTypeAdapter(ApiResult.class, new ApiResultDeserializer())
.create();
List<NavItem> navItems = new ArrayList<NavItem>();
for(int i = 1 ; i < 6 ; ++i) {
navItems.add(new NavItem(i+"", "Name-" + i, "Icon-" + i ));
}
ApiResult result = new ApiResult();
result.status = "OK";
result.data = navItems;
// Serialization
System.out.println(gson.toJson(result)); // {\"status\":\"OK\",\"data\":[{\"id\":\"1\",\"name\":\"Name-1\",\"icon\":\"Icon-1\"},{\"id\":\"2\",\"name\":\"Name-2\",\"icon\":\"Icon-2\"},{\"id\":\"3\",\"name\":\"Name-3\",\"icon\":\"Icon-3\"},{\"id\":\"4\",\"name\":\"Name-4\",\"icon\":\"Icon-4\"},{\"id\":\"5\",\"name\":\"Name-5\",\"icon\":\"Icon-5\"}]}
result.data = navItems.get(0);
System.out.println(gson.toJson(result)); // {\"status\":\"OK\",\"data\":{\"id\":\"1\",\"name\":\"Name-1\",\"icon\":\"Icon-1\"}}
result.data = "Test";
System.out.println(gson.toJson(result)); // {\"status\":\"OK\",\"data\":\"Test\"}
// Deserialization
String input = "{\"status\":\"OK\",\"data\":[{\"id\":\"1\",\"name\":\"Name-1\",\"icon\":\"Icon-1\"},{\"id\":\"2\",\"name\":\"Name-2\",\"icon\":\"Icon-2\"},{\"id\":\"3\",\"name\":\"Name-3\",\"icon\":\"Icon-3\"},{\"id\":\"4\",\"name\":\"Name-4\",\"icon\":\"Icon-4\"},{\"id\":\"5\",\"name\":\"Name-5\",\"icon\":\"Icon-5\"}]}";
ApiResult newResult = gson.fromJson(input, ApiResult.class);
System.out.println(newResult.data); // Array
input = "{\"status\":\"OK\",\"data\":{\"id\":\"1\",\"name\":\"Name-1\",\"icon\":\"Icon-1\"}}";
newResult = gson.fromJson(input, ApiResult.class);
System.out.println(newResult.data); // Object
input = "{\"status\":\"OK\",\"data\":\"Test\"}";
newResult = gson.fromJson(input, ApiResult.class);
System.out.println(newResult.data); // String
I managed to make it work as I wanted, and without using any custom deserializer!
For each endpoint, I wait for the response (btw I'm using Volley), then I first generate the "root" ApiResult object, check if the status is OK, then I proceed instantiating the data field as the requested type.
The POJOs are the same of the question. In ApiResult, "data" is a JsonElement.
// ... called the endpoint that returns a NavItem list
public void onResponse(String response) {
ApiResult rootResult = gson.fromJson(response.toString(), ApiResult.class);
if (rootResult.status.equals(STATUS_OK)) {
Log.d(LOG_TAG, response.toString());
NavItem.List resData = gson.fromJson(rootResult.data, NavItem.List.class); // <-- !!!!!
callback.onSuccess(resData);
}
else {
Log.e(LOG_TAG, response.toString());
callback.onError(-1, null);
}
}
Obviously the only thing to change for the "Profile" endpoint is the line with !!!!!

GSON parse array of array into Java array of object

I have an JSON array of arrays where none of the elements are named (it's just a pure array)
[
["http://test.com/","rj76-22dk"],
["http://othertest.com/","v287-28n3"]
]
In Java, I'd like to parse this JSON into an array of connectionobjs, where the connectionobj class looks like this:
public static class connectionOptions {
String URL, RESID;
}
I looked through the GSON documentation, but couldn't seem to find anything pertinent to parsing a JSON array into anything other than another Java Array. I want to parse the JSON array into a Java Object, not an array.
Is there a way to do this using Google's GSON?
I don't recommend this at all. You should try to have appropriate JSON that maps correctly to Pojos.
If you can't change your JSON format, you'll need to register a custom TypeAdapter that can do the conversion. Something like
class ConnectionOptionsTypeAdapter extends TypeAdapter<ConnectionOptions> {
#Override
public void write(JsonWriter out, ConnectionOptions value)
throws IOException {
// implement if you need it
}
#Override
public ConnectionOptions read(JsonReader in) throws IOException {
final ConnectionOptions connectionOptions = new ConnectionOptions();
in.beginArray();
connectionOptions.URL = in.nextString();
connectionOptions.RESID = in.nextString();
in.endArray();
return connectionOptions;
}
}
Then just register it
GsonBuilder gsonBuilder = new GsonBuilder().registerTypeAdapter(
ConnectionOptions.class, new ConnectionOptionsTypeAdapter());
Gson gson = gsonBuilder.create();
and use it.
Deserialize your JSON as an ConnectionOptions[] or List<ConnectionOptions>.
I've change your class name to ConnectionOptions to follow Java naming conventions.
You should give a customized Deserializer.
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.Collection;
public class TestGson {
public static class ConnectionOptions {
String URL, RESID;
#Override
public String toString() {
return "ConnectionOptions{URL='" + URL + "', RESID='" + RESID + "'}";
}
}
private static class ConnOptsDeserializer implements JsonDeserializer<ConnectionOptions> {
#Override
public ConnectionOptions deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
ConnectionOptions connOpts = new TestGson.ConnectionOptions();
JsonArray array = json.getAsJsonArray();
connOpts.URL = array.get(0).getAsString();
connOpts.RESID = array.get(1).getAsString();
return connOpts;
}
}
public static void main(String[] args) {
String json = "[[\"http://test.com/\",\"rj76-22dk\"],\n" +
" [\"http://othertest.com/\",\"v287-28n3\"]]";
GsonBuilder gsonb = new GsonBuilder();
gsonb.registerTypeAdapter(ConnectionOptions.class, new ConnOptsDeserializer());
Gson gson = gsonb.create();
Type collectionType = new TypeToken<Collection<ConnectionOptions>>(){}.getType();
Collection<ConnectionOptions> connList = gson.fromJson(json, collectionType);
System.out.println("connList = " + connList);
}
}

Categories

Resources