You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用SwiftyJSON解析并打印指定JSON中的url字段(Alamofire环境)

Printing a URL from JSON using SwiftyJSON

Hey there! I see you've already nailed accessing the URL value with SwiftyJSON—printing it out is super straightforward. Let's walk through this:

Basic Print (Using Your Existing Code)

Since you've already assigned the URL to self.documentsDriver, you can just print that variable directly:

// Your existing code to retrieve the URL
self.documentsDriver = json["documents"]["driver"][0]["provider_document"]["url"].stringValue

// Print the URL to the console
print("Driver Document URL: \(self.documentsDriver)")

Safer Approach (Handling Null Values)

Looking at your JSON data, some entries have provider_document: null. Using .stringValue will return an empty string in those cases, which might not be ideal. For a more robust solution, use optional binding to check if the value exists first:

// Check if provider_document exists and is a valid dictionary
if let providerDocument = json["documents"]["driver"][0]["provider_document"].dictionary,
   // Extract the URL string only if it exists
   let documentURL = providerDocument["url"]?.string {
    // Print the valid URL
    print("Valid Driver Document URL: \(documentURL)")
    // Assign it to your variable if needed
    self.documentsDriver = documentURL
} else {
    // Handle cases where the URL or provider_document is missing
    print("No valid URL found for this driver document (provider_document may be null)")
}

This approach lets you gracefully handle entries where provider_document is null, avoiding unexpected empty strings in your output.

内容的提问来源于stack exchange,提问作者Rashed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:29:01