簡體   English   中英

如何打印一些數據值? [迅速]

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

我現在正在使用URLSession 我想只打印profile的中間值, userIdprofile中的數據值在這里。 我怎樣才能打印出來?

我的一些代碼

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) ??"") <當我運行這段代碼時,我得到了這樣的結果。 userIdprofile我只想顯示不包括 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM