【问题标题】:Parse JSON response with SwiftyJSON使用 SwiftyJSON 解析 JSON 响应
【发布时间】:2020-12-22 23:06:55
【问题描述】:

我有以下代码,我正在尝试使用 SwiftyJSON 获取值:

let string =
    """
        {"ResponseMetadata": {"RequestId": "b5d6ecad-e050-4d1f-8429-74a2775a6fe9", "HTTPStatusCode": 200, "HTTPHeaders": {"x-amzn-requestid": "b5d6ecad-e050-4d1f-8429-74a2775a6fe9", "content-type": "application/json", "content-length": "271", "date": "Tue, 22 Dec 2020 22:45:17 GMT"}, "RetryAttempts": 0}, "numberOfRecordsUpdated": 0, "records": [[{"stringValue": "6998DFFE-A9CF-4BEA-86AD-C356BB865E27"}, {"stringValue": "david.craine@yahoo.com"}, {"stringValue": "David"}, {"stringValue": "Craine"}, {"stringValue": "dcraine"}, {"stringValue": "vendor1"}, {"stringValue": "vendor1_werw8"}]]}
    """
    
let body = JSON(string)
print(">>>>>>>>> \(body["records"])")

这将为 body["records"] 返回 null。

我使用https://jsonformatter.curiousconcept.com/# 验证了这个回复,所以我假设它的格式正确。有人可以帮忙吗?

【问题讨论】:

  • “但是,当我尝试获取任何项目(例如“记录”)时,它返回 null”您是如何尝试做到这一点的?
  • 假设提到的字符串的 JSON 对象称为 body ,我使用 body["records"]
  • 我会推荐你​​使用 Swift 的 Codable & JSONDecoder,这将允许你在不使用任何第三方框架的情况下解析和创建 JSON
  • 尝试用let body = JSON(parseJSON: string)替换let body = JSON(string)
  • 感谢@gcharita,它正在工作!如果您发布您的答案,我将标记为正确。

标签: json swift aws-api-gateway aws-amplify swifty-json


【解决方案1】:

尝试更改此行:

let body = JSON(string)

并调用JSONinit(parseJSON:) 初始化程序,它以String 作为参数,如下所示:

let body = JSON(parseJSON: string)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    相关资源
    最近更新 更多