尝试使用Swift 4.2对此JSON
进行解码时遇到很多麻烦:
{
token = a3253e6ade9b5c7fd99673938bb28b3e;
user = {
"about_me" = Admin;
address = "";
"banner_path" = "http://members.sharjahcd.ae/images/000/000/008/1540737652129.jpg?1541043871";
company = "<null>";
description = "<null>";
email = "admin@stf.com";
"events_count" = 0;
"followers_count" = 0;
"following_count" = 0;
id = 2;
"image_path" = "http://members.sharjahcd.ae/images/000/000/009/1540737834886.jpg?1541043896";
"is_admin" = 1;
major = "";
"my_post_count" = 5;
name = "Admin MemberPortal";
"non_business_email" = "<null>";
passedout = "";
"phone_number" = 000000000;
photos = (
"http://members.sharjahcd.ae/images/000/000/004/IMG_20181029_150700.jpg?1540805844",
"http://members.sharjahcd.ae/images/000/000/012/20181028_173702.jpg?1541126171",
"http://members.sharjahcd.ae/images/000/000/011/20181028_173703.jpg?1541126151",
"http://members.sharjahcd.ae/images/000/000/010/20181028_173705.jpg?1541126144"
);
position = "<null>";
role = Admin;
stars = 3;
"total_membership_points" = 0;
};
}
这是如何尝试对其进行解码
let UserDatas = try JSONDecoder().decode(Token.self, from: data)
print("response : \(UserDatas)")
struct Token: Decodable {
let token: String
let user: [Response]
}
struct Response: Decodable {
let about_me: String
let address: String
let company: String
let description: String
let email: String
let events_count: Int
let followers_count: Int
let following_count: Int
let id = Int()
let image_path: String
let is_admin: String
let major: String
let my_post_count: Int
let name: String
let non_business_email: String
let passedout: String
let phone_number: Int
let photos: [String]
let position: String
let role: String
let stars: Int
let total_membership_points: Int
}
它不起作用并出现以下错误:
typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:“ user”,intValue:nil)]],debugDescription:“希望对Array进行解码,但是找到了一个字典。”,底层错误:nil ))
我如何制作将解码此JSON的结构?
答案 0 :(得分:2)
在JSON中,用户属性不是数组,但是在代码中将其声明为数组([Response]
)。将您的代码更改为:
struct Token: Decodable {
let token: String
let user: Response
}
此外,如果您在代码中声明的任何属性为JSON中的null或缺失,则应将其设置为可选。
在您的JSON中,公司似乎为空,因此请更改
let company: String
到
let company: String?
并对其他可能为null或缺失的属性执行相同的操作。
答案 1 :(得分:1)
您可能还想使用CodingKey
。
struct Landmark: Codable {
var name: String
var foundingYear: Int
var location: Coordinate
var vantagePoints: [Coordinate]
enum CodingKeys: String, CodingKey {
case name = "title"
case foundingYear = "founding_date"
case location
case vantagePoints
}
}