[英]How can I print some values of data? [Swift]
我现在正在使用URLSession
。 我想只打印profile
的中间值, userId
和profile
中的数据值在这里。 我怎样才能打印出来?
我的一些代码
if let httpResponse = response as? HTTPURLResponse {
print( httpResponse.allHeaderFields )
guard let data = data else {return}
print( String (data: data, encoding: .utf8) ?? "" )
let profile = "{\"profile\":\"\(data.profile ?? "")}" // ERROR [Value of type 'Data' has no member 'profile']
}
print (String (data: data, encoding: .utf8) ??"") <当我运行这段代码时,我得到了这样的结果。 userId
和profile
我只想显示不包括 userId only the profile
。 谢谢阅读。
我会定义一个符合 Codable 协议的类型,并使用 JSONDecoder 将您的数据解码为用户友好的内容。
struct UserData: Codable {
let userId: String
let profile: String
}
以下是解码数据的方法:
if let httpResponse = response as? HTTPURLResponse {
guard let data = data else { return }
let decoder = JSONDecoder()
do {
let userData = try decoder.decode(UserData.self, from: data)
print(userData.profile)
} catch {
print("Error: \(error)")
}
}
您可以将数据转换为 json 并根据需要使用
json = try JSON(data: data)
如果您想轻松解析它,请使用 SwiftyJson
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.