How convert struct to string (valid url format) and then parse the same struct again from it?

I want to convert my structs to the "string" so I can add them to the URL and reread them later from another URL.

here is how I wanted to do it, but it’s not working and I have no idea why.

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")
}

Output:

stringData: https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=

validURL: https:google.com/https:google.com/eyJumluZyI6WyJpdGVtIDEiLCJpdGVtIDIiXX0=

shit!

>Solution :

It’s a typo. You have to decode newData rather than newStringData

You can figure out yourself if you catch the DecodingError.

And it’s easier to get the path of the URL and drop the first – the slash – character

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?.path.dropFirst().data(using: .utf8) {
    let newData = Data(base64Encoded: newStringData)!
    do {
        let newObject = try JSONDecoder().decode(MyObject.self, from: newData)
        print("new parsed object:", newObject)
    } catch {
        print("shit!", error)
    }
} else {
    print("Oops")
}

Leave a Reply