[英]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.