繁体   English   中英

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

[英]How to change the json structure created by Gson in java

由对象列表的Gson创建的json看起来像。

"[[{"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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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