我有一個編碼字串:
("[{"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","re??gistrationNo":"4325","insuranceProvider":"Buttler","carModel":"A3"}]")
我想將其轉換為 JSON 陣列,如下所示:
[
{
"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"
}
]
經過一番搜索,我所做的是將其轉換為字典,結果是:
[[“registrationNo”:02134,“carModel”:奔馳,“電話”:03001234567,“電子郵件”:[email protected],“insuranceProvider”:邁克爾,“insurancePolicyNo”:0123456,“carMake”:梅賽德斯,“full_name ": Steven Finn], ["carModel": A3, "insuranceProvider": Buttler, "carMake": Audi, "insurancePolicyNo": 654321, "full_name": Flemming Smith, "registrationNo": 4325, "phone": 03007654321, “電子郵件”:[email protected]]]
這不是預期的結果。
有誰知道如何實作我想要的陣列?
uj5u.com熱心網友回復:
你所謂Encoded String的已經是json資料了。試試這個把它解碼成一個Car模型:
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)")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/494630.html
