<Object> 使用 Gson 将 ArrayList 转换为 Json



首先,我对编程很陌生。对于学校,我正在研究一个Android项目,我希望能够使用SharedPreferences保存数据,使用Gson将ArrayList转换为Json。但是,每当我尝试运行它(模拟器(时,我都会在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

这将持续一段时间,直到我的应用程序崩溃。在以与我在这里尝试相同的方式保存其他数据时,我没有遇到此问题。

法典:

将对象添加到数组

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

转换和保存

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

这里可能有什么问题?

试试这个

Type listType = new TypeToken<ArrayList<YourObject>>(){}.getType();
listGalerias = new Gson().fromJson(json, listType);

好的,我在这里尝试了这样的东西,我有一个带有一些字段的对象帖子,我使用 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

结果是这样的 帖子对象

后来我做了这个

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)

结果是这样的 我的对象Json已填充

这是 对象Json值

最新更新