gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:05:27 25 4
gpt4 key购买 nike

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)

关于java - 如何更改java中Gson创建的json结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33008131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com