Home > OS >  Convert Encoded String To JSON Array in Swift
Convert Encoded String To JSON Array in Swift

Time:06-22

I have an Encoded String:

("[{"carMake":"Mercedes","phone":"03001234567","insurancePolicyNo":"0123456","email":"[email protected]","full_name":"Steven Fin","registrationNo":"02134","insuranceProvider":"Michael","carModel":"Benz"}, {"carMake":"Audi","phone":"03007654321","insurancePolicyNo":"654321","email":"[email protected]","full_name":"Flemming Smith","registrationNo":"4325","insuranceProvider":"Buttler","carModel":"A3"}]")

I want to convert this into JSON array like this:

 [
    {
      "full_name": "Steven Finn",
      "insuranceProvider": "Michael",
      "insurancePolicyNo": "0123456",
      "registrationNo": "02134",
      "carMake": "Mercedes",
      "carModel": "Benz",
      "email": "[email protected]",
      "phone": "03001234567"
    },
    {
      "full_name": "Flemming Smith",
      "insuranceProvider": "Buttler",
      "insurancePolicyNo": "654321",
      "registrationNo": "4325",
      "carMake": "Audi",
      "carModel": "A3",
      "email": "[email protected]",
      "phone": "03007654321"
    }
  ]

After some searching, what I did was converting it to Dictionary, which results in:

[["registrationNo": 02134, "carModel": Benz, "phone": 03001234567, "email": [email protected], "insuranceProvider": Michael, "insurancePolicyNo": 0123456, "carMake": Mercedes, "full_name": Steven Finn], ["carModel": A3, "insuranceProvider": Buttler, "carMake": Audi, "insurancePolicyNo": 654321, "full_name": Flemming Smith, "registrationNo": 4325, "phone": 03007654321, "email": [email protected]]]

Which is not the desired result.

Did anyone knows how to achieve my desired array?

CodePudding user response:

your so called Encoded String is already json data. Try this to decode it into a Car model:

struct Car: Codable {
    let carMake, phone, insurancePolicyNo, email: String
    let full_name, registrationNo, insuranceProvider, carModel: String
}

struct ContentView: View {
    var body: some View {
        Text("testing")
            .onAppear {
                let str = """
                 [{"carMake":"Mercedes","phone":"03001234567","insurancePolicyNo":"0123456","email":"[email protected]","full_name":"Steven Fin","registrationNo":"02134","insuranceProvider":"Michael","carModel":"Benz"}, {"carMake":"Audi","phone":"03007654321","insurancePolicyNo":"654321","email":"[email protected]","full_name":"Flemming Smith","registrationNo":"4325","insuranceProvider":"Buttler","carModel":"A3"}]
                 """
                
                do {
                    let data = str.data(using: .utf8)!
                    let response = try JSONDecoder().decode([Car].self, from: data)
                    print("\n---> response \(response)")
                } catch {
                    print(" error \(error)")
                }
  • Related