如何将结构转换为字符串(有效的url格式),然后从中再次解析相同的结构?

问题描述 投票:0回答:1

我想将我的结构转换为“字符串”,以便我可以将它们添加到 URL 并稍后从另一个 URL 重新读取它们。

这就是我想做的,但它不起作用,我不知道为什么。

struct MyObject: Codable {
    var number: Int
    var title: String
    var arrayString: [String]
}
let myObject = MyObject(number: 2, title: "hello", arrayString: ["item 1", "item 2"])
let data = try JSONEncoder().encode(myObject)
let stringData = data.base64EncodedString()
print("stringData:", stringData)
let validURL = URL(string: "https:google.com/" + stringData)
print("validURL:", validURL?.absoluteString ?? "")

if let newStringData = validURL?.absoluteString.replacingOccurrences(of: "https:google.com/", with: "").data(using: .utf8) {
    let newData = Data(base64Encoded: newStringData)
    if let newObject = try? JSONDecoder().decode(MyObject.self, from: newStringData) {
        print("new parsed object:", newObject)
    } else {
        print("shit!")
    }
} else {
    print("Oops")
}

输出:

字符串数据:https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=

有效网址:https:google.com/https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=

妈的!

swift struct decode encode
1个回答
0
投票

这是一个错字。你必须解码

newData
而不是
newStringData 

let newData = Data(base64Encoded: newStringData)!
if let newObject = try? JSONDecoder().decode(MyObject.self, from: newData) {
© www.soinside.com 2019 - 2024. All rights reserved.