I need to parse below sample strings to get status and code and bind it to a struct "ErrorData".
String1 - ("{\n \"errors\": [ {\n \"status\": \"400\",\n \"code\": \"INVALID_DATA\"\n } ]\n}")
String2 - "{\n \"errors\": [ {\n \"status\": \"404\",\n \"code\": \"INVALID_AUTH\"\n } ]\n}")
public struct ErrorData {
var errorStatus: String?
var errorCode: String?
}
These are only 2 samples string, there will be many more strings of same format with different status and code value. How do I parse above string with format as shown above.
This is JSON. These structs match the data
struct ErrorData : Decodable {
let errors : [ErrorItem]
}
struct ErrorItem : Decodable {
let status, code : String
}
Parse it with
let jsonString = """
{"errors":[{"status":"400","code":"INVALID_DATA"}]}
"""
do {
let result = try JSONDecoder().decode(ErrorData.self, from: Data(jsonString.utf8))
for item in result.errors {
print(item.status, item.code)
}
} catch {
print(error)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.