如何更改 Gson 在 java 中创建的 json 结构

How to change the json structure created by Gson in java

json 对象列表的 Gson 创建的样子。

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

但我希望它看起来像

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

我用这样的 Gson 库创建了这个 json。

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);

我想要这个特定的结构json,这样它就可以直接转换为Dog类型的RealmList。

 realm.createOrUpdateAllFromJson(Dog.class, jsonStr);

你从你的 query 得到的东西类似于 List<List<Dog>> 您需要 List<Dog> 才能获得 JSON,试试这个变体

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));

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