简体   繁体   English

如何打印一些数据值? [迅速]

[英]How can I print some values ​of data? [Swift]

I am using URLSession right now.我现在正在使用URLSession I want to print only the profile value among the userId and profile in the data value here.我想只打印profile的中间值, userIdprofile中的数据值在这里。 How can I print it?我怎样才能打印出来?

Some of my code我的一些代码

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) ??"") <When I run this code, I get the result like this. print (String (data: data, encoding: .utf8) ??"") <当我运行这段代码时,我得到了这样的结果。 userId and profile I want to display only the profile excluding the userId. userIdprofile我只想显示不包括 userId only the profile Thanks for reading.谢谢阅读。 在此处输入图片说明

I'd define a type conforming to the Codable protocol and use a JSONDecoder to decode your data to something user friendly.我会定义一个符合 Codable 协议的类型,并使用 JSONDecoder 将您的数据解码为用户友好的内容。

struct UserData: Codable {
    let userId: String
    let profile: String
}

Here's how to decode your data:以下是解码数据的方法:

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)")
    }
}

You can convert data to json and use however you want您可以将数据转换为 json 并根据需要使用

json = try JSON(data: data) 

if you want to parse it easily use SwiftyJson如果您想轻松解析它,请使用 SwiftyJson

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM