'how to parse response string with different data in swift 5
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.
Solution 1:[1]
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)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | vadian |
