簡體   English   中英

如何正確地將對象數組序列化和反序列化到/從json中?

[英]How to properly serialize and deserialize an array of objects into/from json?

我正在嘗試使用 libgdx 在 Kotlin/Java 中實現需要存儲在 .json 文件中的朋友列表,但這不是必需的(Java 很好)。 我的 (1) 代碼不起作用,所以我不會在這里粘貼它,而是嘗試解釋我的設計並只粘貼 (2) 的代碼,因為我認為這更接近於一個好的實現。

  1. 我做了一個“朋友”類。 添加新朋友時,主線程創建了這樣一個對象,然后我將現有的“FriendsList.json”讀入一個字符串,通過刪除“]”編輯字符串並附加序列化的朋友對象和一個“]”以關閉數組. 我曾經並且仍然覺得這不好,所以我改變了它。
  2. 我創建了一個“FriendArray”類,我想在其中將“Friend”對象存儲在一個列表中。 我認為這將允許我擺脫字符串操作代碼,而只需序列化 FriendList 類本身,這也有望更容易閱讀。 問題之一是 addFriendToListOfFriends() 不會在對象中添加數據(它添加“{}”而不是插入名稱和 ID)。

你覺得 (2) 怎么樣? 你知道更好的方法嗎?

(為了清楚起見,我對設計更感興趣,而不是可編譯代碼)

import com.badlogic.gdx.files.FileHandle
import com.unciv.json.json (this is com.badlogic.gdx.utils.Json)
import java.io.Serializable

class FriendList() {
    private val friendsListFileName = "FriendsList.json"
    private val friendsListFileHandle = FileHandle(friendsListFileName)
    private var friendListString = ""

    var arrayOfFriends = FriendArray()

    fun getFriendsListAsString(): String {
        return friendsListFileHandle.readString()
    }

    fun addNewFriend(friendName: String, playerID: String) {
        val friend = Friend(friendName, playerID)
        arrayOfFriends.addFriendToListOfFriends(friendName, playerID)
        saveFriendsList()
    }

    fun saveFriendsList(){
        friendListString = getFriendsListAsString()

        friendListString = friendListString.plus(json().prettyPrint(arrayOfFriends))

        friendsListFileHandle.writeString(friendListString, false)
    }
}

class Friend(val name: String, val userId: String)

class FriendArray(): Serializable {
    var nrOfFriends = 0

    var listOfFriends = listOf<Friend>()

    fun addFriendToListOfFriends(friendName: String, playerID: String) {
        var friend = Friend(friendName, playerID)
        listOfFriends.plus(friend)
    }
}

你真的不需要一個 FriendArray 類。 您可以將列表序列化為 JSON。 此外,將現有朋友列表加載到列表中,將新朋友添加到列表中並序列化新列表,而不是附加字符串更容易。
這樣您就不必擔心正確的 JSON 格式或字符串操作。 您只需將一個對象添加到列表中,然后序列化該列表。

像這樣的東西應該可以工作(在java中,抱歉我不知道足夠的kotlin來實現這個):

public void addFriendAndSerializeToFile(Friend friend) {
    // load existing friend list from the file
    Json json = new Json();
    // here the first parameter is the List (or Collection) type and the second parameter is the type of the objects that are stored in the list
    List<Friend> friendList = json.fromJson(List.class, Friend.class, friendsListFileHandle);
    
    // add the new friend to the deserialized list
    friendList.add(friend);

    // serialize the whole new list to the file
    String serializedFriendListWithNewFriendAdded = json.prettyPrint(friendList);
    
    // write to the file handle
    fileHandle.writeString(serializedFriendListWithNewFriendAdded, false);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM