【问题标题】:Not able to get the stringValue in arguments with SwiftyJSON无法使用 SwiftyJSON 获取参数中的 stringValue
【发布时间】:2016-01-26 17:06:27
【问题描述】:
{
  "StatusResponse": 
  {
     "StatusCode": "000"
     "StatusDescription": "Operation Success(000)"
     "DebugDescription": "OperationSuccess"
  }-
"memId": "3e369fec-a9c5-418b-a950-0647f7e15d7c"
"token": null
"isAdmin": false
"isTeacher": false
"isParent": true
"kinderId": null
}

这是我的 JSON 格式

Alamofire.request(.GET, "myURL").responseJSON { response in
            switch response.result {
            case .Success(let data):
                let json = JSON(data)
                let memId = json["memId"].stringValue
                for result in json["StatusResponse"].arrayValue
                {
                    let code = result["StatusCode"].stringValue
                    print("code = \(code)")
                }
                print("memId : \(memId)")
            case .Failure(let error):
                print("Request failed with error: \(error)")
            }
        }

我的代码和其他代码中有一个 StatusResponse 参数,但是,我可以获取 memId 字符串值,我的代码有任何问题,为什么我无法在此处获取 StatusCode?​​p>

【问题讨论】:

  • StatusResponse 是字典而不是 arrayValue。

标签: ios json swift swifty-json


【解决方案1】:

StatusResponse 是字典而不是 arrayValue,试试这个:

let code = json["StatusResponse"]["StatusCode"].stringValue

【讨论】:

  • 谢谢老兄,但我在没有 if 语句的情况下更改了它...如果这里的语句会出错。非常感谢
  • 当我将 stringValue 替换为 string 时,我编辑了它对我有用的答案。
【解决方案2】:

在该 JSON 示例中,StatusResponse 似乎是一个字典,而不是一个数组。

编辑:我的 Swift 现在有点生疏了,但大致应该是这样的:

Alamofire.request(.GET, "myURL").responseJSON { response in
        switch response.result {
        case .Success(let data):
            let json = JSON(data)
            let memId = json["memId"].stringValue
            if let statusResponse = json["StatusResponse"] as? NSDictionary 
            {
                let code = statusResponse["StatusCode"].stringValue
                print("code = \(code)")
            }
            print("memId : \(memId)")
        case .Failure(let error):
            print("Request failed with error: \(error)")
        }
    }

【讨论】:

  • 那么有没有可能获取StatusCode的stringValue的方法?
  • 但是 NSDictionary 不能从 JSON Xcode 中强制转换说
【解决方案3】:

我对 JSON 格式有点困惑。第三个括号后面的“-”是什么?

如果 JSON 是这样的:

{
  "StatusResponse": 
  {
     "StatusCode": "000"
     "StatusDescription": "Operation Success(000)"
     "DebugDescription": "OperationSuccess"
  },
"memId": "3e369fec-a9c5-418b-a950-0647f7e15d7c",
"token": null,
"isAdmin": false,
"isTeacher": false,
"isParent": true,
"kinderId": null
}

那么 memId 不是 StatusResponse 对象的端口,因此您应该先解包它来获取值(因为它可以为 null)。

guard let memId = json["memId"] as? String else {
    // manage case memId == null
}

print("My memId: \(memId)")

希望这会有所帮助!

【讨论】:

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