简体   繁体   English

转换ArrayList <Object> 使用Gson进入Json

[英]Converting ArrayList<Object> into Json using Gson

To start off, i'm reasonable new to programming in general. 首先,我是一般编程新手。 For school i'm working on an android project in which i would like to be able to save data using SharedPreferences, using Gson to turn an ArrayList into Json. 对于学校,我正在研究一个android项目,我希望能够使用SharedPreferences保存数据,并使用Gson将ArrayList转换为Json。 However, whenever I try to run it (emulator) I get the following messages in logcat: 但是,每当我尝试运行它(仿真器)时,我都会在logcat中收到以下消息:

Do full code cache collection, code=125KB, data=66KB
After code cache collection, code=104KB, data=41KB
Background concurrent copying GC freed 36221(1156KB) AllocSpace objects, 3(60KB) LOS objects, 49% free, 1708KB/3MB, paused 5.863ms total 115.252ms
Do partial code cache collection, code=123KB, data=56KB
After code cache collection, code=123KB, data=56KB
Increasing code cache capacity to 512KB

This will go on for a while untill my app crashes. 这将持续一段时间,直到我的应用程序崩溃为止。 I do not run into this problem when saving other data the same way I'm trying to do here. 当我以其他方式保存其他数据时,我没有遇到这个问题。

Code: 码:

adding objects to array 将对象添加到数组

for(int x = 0; x < board.getWidth(); x++ ) {
                for( int y = 0; y < board.getHeight(); y++ ) {

                    Field field = (Field) MainActivity.game.getGameBoard().getObject(x, y);
                    fieldArray.add(field);
                }
            }

converting and saving 转换并保存

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = prefs.edit();
Gson objectGson = new Gson();
String objectJson = objectGson.toJson(fieldArray);
edits.putString("gameobjects", objectJson);
editor.apply();

What could be the problem here? 这可能是什么问题?

Try this 尝试这个

Type listType = new TypeToken<ArrayList<YourObject>>(){}.getType();

listGalerias = new Gson().fromJson(json, listType);

Ok, I tried here something like this, I have an object Post with some fields, I used Gson to populate this object 好的,我在这里尝试过类似的操作,我有一个带有一些字段的Post对象,我用Gson填充了这个对象

val url = "http://www.projectconnect.com.br/make/api/post/list/list.php"

val json = URL(url).readText()

val gson = Gson()

val retorno = gson.fromJson(json, Retorno::class.java)

val posts : List<Post> = retorno.list

the result was this Post object 结果是这个Post对象

later I made this 后来我做了这个

val arrayPosts = arrayOfNulls<Post>(posts.size)
arrayPosts.set(0, posts[0])

for (i in 0 until posts.size) {
    arrayPosts[i] = posts[i]
}

val objectJson = gson.toJson(arrayPosts)

and the result was this my objectJson populated 结果就是这个我的对象

here is the objectJson value 这是objectJson值

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

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