我有一个可迭代的People
,从json转换后我另存为string
。我想知道如何将string
转换回列表。
// Save data
val peopleString = myList.toString()
// String saved is
[People(name=john, age=23), People(name=mary, age=21), People(name=george, age=11)]
现在可以将
peopleString
转换回列表吗?val peopleList: List<People> = peopleString.?
最佳答案
简而言之,不...有点。
您的输出不是JSON,如果需要JSON,则toString()
是使用错误的函数。 toString()
的输出不是可以理解并用于重建原始数据结构的正确序列化格式。
将数据结构转换为某种格式以便可以传输并稍后重建的过程称为serialization。 Kotlin有一个序列化程序,可以将对象序列化为多种不同格式,包括JSON:https://github.com/Kotlin/kotlinx.serialization#quick-example。
它不像toString()
那样容易使用,但这是可以预期的,因为toStrings
的目的与序列化有很大不同。
关于kotlin - Kotlin将String转换为Iterable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49724226/