I'm trying to parse a json file in swift. Its body looks like that and I still receive no data! Can any one tell me how the structs should looks like? What am i missing?
This is the received json:
{
"blocked_list": {
"total": 2,
"users": [
{
"id": 49,
"name": "fdewer12faasd",
"profilePicture": "",
"followStatus": 0
}
]
}
}
This is the json parsing code:
func parseJSON(_ blockdata: Data) -> CurrentUserBlockListModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(CurrentUserBlockList.self, from: blockdata)
let usersArray = decodedData.users
let count = decodedData.total
let blockModel = CurrentUserBlockListModel(users: usersArray,total:count)
return blockModel
} catch {
print("error ")
return nil
}
}
These are my structs:
struct CurrentUserBlockList : Codable {
let total : Int?
let users : [users]
}
struct users : Codable {
let followStatus : Int?
let id : Int?
let name : String?
let profilePicture : String?
}
The object you are trying to decode is wrongly defined.
If use your Parsing Code
, make new Struct
struct SolutionObject: Codable {
let blocked_list: CurrentUserBlockList
}
struct CurrentUserBlockList : Codable {
let total : Int?
let users : [users]
}
struct users : Codable {
let followStatus : Int?
let id : Int?
let name : String?
let profilePicture : String?
}
And change your parsing Code
CurrentUserBlockList
--> SolutionObject
func parseJSON(_ blockdata: Data) -> CurrentUserBlockListModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(SolutionObject.self, from: blockdata)
let usersArray: [users] = decodedData.blocked_list.users
let count: Int? = decodedData.blocked_list.total
guard let count = count else {
return nil
}
let blockModel = CurrentUserBlockListModel(users: usersArray, total: count)
return blockModel
} catch {
print("error")
return nil
}
}
JSON is basically made of key and value pairs.
and
Use the Optional Carefully.
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.