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

Swift中解析API响应字符串转JSON时遇错误求助

解决iOS Swift解析API响应为JSON模型的问题

Hey there! Let's work through this parsing issue you're facing. I see you're using Alamofire and SwiftyJSON-based model classes, but the problem comes down to how you're handling the API response data.

问题根源

You're using responseString to get the API result, which gives you a raw string—but your DealModelRootClass expects a SwiftyJSON JSON object to initialize itself. Right now, you're passing that raw string to your completion handler, which means whoever is receiving it doesn't have the properly formatted JSON object needed for the model.

解决方案步骤

1. 改用Alamofire的responseJSON直接获取JSON对象

Instead of dealing with raw strings, let Alamofire parse the response into a JSON-compatible object automatically. Then we can convert it to a SwiftyJSON instance and initialize your model directly:

// 先调整你的completion类型为返回DealModelRootClass?,而不是String?
Alamofire.request(url).responseJSON { response in 
    guard response.result.isSuccess, let jsonRawValue = response.result.value else { 
        print("Error while fetching tags: \(String(describing: response.result.error))") 
        completion(nil) 
        return 
    }
    // 把原生JSON值转换成SwiftyJSON的JSON对象
    let json = JSON(jsonRawValue)
    // 直接初始化你的根模型
    let dealRootModel = DealModelRootClass(fromJson: json)
    completion(dealRootModel)
}

2. 确保子模型正确处理数组

Double-check your DealDataModelRootClass to make sure it properly handles the deals array from the JSON. It should have a property like:

var deals: [DealItemModel]! // 替换成你的子模型类名

And in its init(fromJson json: JSON!) method, you should loop through the deals JSON array to initialize each sub-model:

let dealsArray = json["deals"].arrayValue
deals = [DealItemModel]()
for dealJson in dealsArray {
    let dealItem = DealItemModel(fromJson: dealJson)
    deals.append(dealItem)
}

3. 处理HTML转义字符(可选)

Notice your response has & instead of & (like in Deal & Discount). If you want to display these correctly, add a quick string replacement after parsing:

// 在模型初始化后处理,比如在DealDataModelRootClass里
title_desc = json["title_desc"].stringValue.replacingOccurrences(of: "&", with: "&")

额外建议

If you're open to it, consider switching to Swift's native Codable protocol instead of custom JSON parsing with SwiftyJSON—it's built into the language, reduces boilerplate code, and is easier to maintain long-term. But if you want to stick with your current setup, the above changes should fix your parsing error.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:44:40