【问题标题】:parsing api response JSON to get content values解析 api 响应 JSON 以获取内容值
【发布时间】:2016-07-19 17:00:33
【问题描述】:

背景

我有一个 ios 应用程序正在接收来自 post call 的响应。我只是想在内容标签中提取 id。但是我在帮助页面上看到的所有语法似乎都不起作用。

self.post("stands/build", data: dataDictionary).responseString { (response) -> Void in
     let responseValue = response.result.value
     let new_data =  JSON(responseValue!)
     print(new_data)
     print(new_data[0])
     print(new_data["message"])
     print(new_data["content"])

打印:

{"message":"Success","content":{"id":351,"user_id":2,"name":"test","creator":null,"size":0,"description":"Test"}}
null
null
null

我正在使用import SwiftyJSON

问题:

什么代码会打印用户 ID:351。

我的印象是 print(new_data["content]["id"]) 可以工作,但它只是给出空值

编辑 1

            if let dataFromString = responseValue!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {

                //SwiftyJSON, construct JSON.
                let json = JSON(data: dataFromString)
                print(json["content"]["id"])

            }

导致此错误:

2016-07-19 14:17:15.888 MYPROJECT[13799:3666542] -[__NSCFDictionary dataUsingEncoding:allowLossyConversion:]: unrecognized selector sent to instance 0x7ffe2e0416a0
2016-07-19 14:17:15.946 MYPROJECT[13799:3666542] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary dataUsingEncoding:allowLossyConversion:]: unrecognized selector sent to instance 0x7ffe2e0416a0'

编辑 2

let id: Int = JSON["content"]["id"].intValue

给出错误instance member 'subscript' cannot be used on type 'JSON'

EDIT 3 差不多了...

self.post("stands/build", data: dataDictionary).responseString { (response) -> Void in
    let responseValue = response.result.value
    let new_dict = (responseValue as! NSDictionary) 
    print(new_dict["content"]!["id"])

打印Optional(356)

如何让它打印 356?

编辑 4

print(new_dict["content"]!["id"]!!.intValue)

有效。

不过,我认为我的解决方案很草率。以下解决方案均无效,但我会支持导致我得到此答案的解决方案。

【问题讨论】:

    标签: json swift swifty-json


    【解决方案1】:

    试试下面的代码

    if let new_data =  JSON(responseValue!) as? NSDictionary{
        let content = new_data["content"] as! NSdictionary 
        let user_id = content[user_id] as! Int  
        print(format:"user_id :: %d",user_id)
    }
    else{ 
       print("no data found..")
    }
    

    【讨论】:

    • 每次都会打印“没有找到数据..”,我试着找出原因
    • @Rorschach 发生这种情况是因为JSON(data: dataFromString) 没有将数据转换为 NSDictionary
    • 你能看看我的问题中的 EDIT 3,我使用了你的部分解决方案来让自己更接近
    【解决方案2】:

    您忘记使用 JSON 对象的 int 属性。

    一个简单的例子:

    if let id: Int = json["someData"]["someValue"].int {
      // id was defined properly
    }
    else {
      print("parsing error: \(json["someData"]["someValue"])")
    }
    

    或者您可以始终使用intValue获得一些价值

    let id: Int = json["someData"]["someValue"].intValue // defines some value or zero as fallback
    

    我希望这可以帮助您解决问题。

    【讨论】:

    • let id: Int = JSON["content"]["id"].intValue 给出错误instance member 'subscript' cannot be used on type 'JSON'
    【解决方案3】:

    从日志中,

    首先,responseValue 不是 JSON 对象,它只是一个 json 字符串。 如果是这样,

    if let dataFromString = responseValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
    
        //SwiftyJSON, construct JSON.
        let json = JSON(data: dataFromString)
        print(json["content"]["id"])
    
    }
    

    这应该可行!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多