![](/img/trans.png)
[英]How to serialize and deserialize Java Enums as JSON objects with Jackson
[英]How to properly serialize and deserialize an array of objects into/from json?
我正在嘗試使用 libgdx 在 Kotlin/Java 中實現需要存儲在 .json 文件中的朋友列表,但這不是必需的(Java 很好)。 我的 (1) 代碼不起作用,所以我不會在這里粘貼它,而是嘗試解釋我的設計並只粘貼 (2) 的代碼,因為我認為這更接近於一個好的實現。
你覺得 (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.