简体   繁体   中英

How to change the json structure created by Gson in java

json created by Gson of List of Objects looks like.

"[[{"id":1,"name":"Shepherd"}],[{"id":2,"name":"Bull"}]]"

But I want this to be look like

"[{'id':1,'name':'Shepherd'},{'id':2,'name':'Bull'}]"

I created this json by using Gson library like this.

class Dog{
long id;
String name;
}

ArrayList<Dog> myDogs= new ArrayList<Dog>();
ArrayList<Object> objects = new ArrayList<Object>();
objects = Application.getApplication.query(Object.class, " from Dog", 0, 0);
//Fetching data through HQL
myDogs=(ArrayList<Dog>)objects;
String jsonStr = new Gson().toJson(myDogs);

I want this specific structured json so that it directly converts to RealmList of Dog type by using.

 realm.createOrUpdateAllFromJson(Dog.class, jsonStr);

What you are getting from your query is something like List<List<Dog>> You need List<Dog> to obtain JSON as you want, try this variant

ArrayList<Object> objects = new ArrayList<Object>();
objects = Application.getApplication.query(Object.class, " from Dog", 0, 0);
//Fetching data through HQL
myDogs=(ArrayList<List<Dog>)objects;
String jsonStr = new Gson().toJson(Iterables.concat(myDogs));

see http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Iterables.html#concat(java.lang.Iterable)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM