【问题标题】:Swift: convert JSON from URL to multiple stringsSwift:将 JSON 从 URL 转换为多个字符串
【发布时间】:2015-06-03 08:31:05
【问题描述】:

我处于摇摆不定的艰难阶段,经过数小时或调查后,我找到了一些信息,但不足以执行我所寻找的。 我正在向服务器发送一个 POST http 请求,这个请求将一个转换为 NSDictionnary 的 JSON 发回给我:

let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &err) as? NSDictionary

为了查看服务器发送给我的内容,我打印了这个 NSString:

let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("**** response data = \(responseString)")

这是它可以返回给我的一个示例:

**** response data = Optional({"result":true,"data":"[{\"id\":\"284ad166f8152268e4010c4cb21c40c13f195165\",\"due\":null,\"description\":\"\",\"status\":\"LATE\",\"summary\":\"tache late\",\"context\":\"\",\"folder\":\"INBOX\"},{\"id\":\"b43bd766295220b23279899d025217d18e98374a\",\"due\":null,\"description\":\"\",\"status\":\"IN-PROCESS\",\"summary\":\"tache in process\",\"context\":\"\",\"folder\":\"INBOX\"}]"}

我寻找的是分离这些信息以获取字符串上的 Id、另一个上的到期日期、另一个上的描述等以将它们打印在 UITableView 上,每个数组一行。

我找到了大量的教程、链接,例如 https://github.com/dankogai/swift-jsonhttp://owensd.io/2014/08/06/functional-json.htmlhttps://github.com/thoughtbot/Argohttp://roadfiresoftware.com/2014/08/a-safer-approach-to-json-parsing-in-swift/but...

我是 swift 编码的新手,这是我使用这种语言的第一个月,我可能错过了关于这个 Json 解析的一些非常简单的东西......

感谢您的帮助。

【问题讨论】:

  • 我强烈推荐 swift-json 库,我将它用于 instagram api,它非常棒!
  • 我曾尝试使用它,但未能成功将其应用于我的 JSON。我会继续努力的。

标签: json swift http parsing url


【解决方案1】:

您可以使用SwiftyJson 或手动操作。你得到了 json,所以你不需要将它转换为 NSString。 首先使用

解开字典
json!

其次,你需要得到你想要的东西。如您所见,您需要从“数据”键中获取值,因此请使用

json!["data"]

接下来你可以访问任何你想要的

if let id = json!["data"]!["id"]! {
  println(id)
}

if let due = json!["data"]!["due"]! {
  println(due)
}

if let description = json!["data"]!["description"]! {
  println(description)
}

现在你可以在你的 UITableViewCell 中表示它。例如,您可以使用id 作为标题,使用due & description 作为内容。

这里唯一重要的是了解如何访问字典中的键和值。

为了避免重复自己,更好的方法是将data 的值存储到一个常量中

let data = json!["data"]!

然后从中取出您喜欢的东西。举个例子

if let id = data["id"]! {
  println(id)
}

这里有一个小例子来告诉你怎么做

let dict = Optional(["data": ["id": "12345", "due": "due date", "description": "some description"]])

let data = dict!["data"]!

println(data["id"]!)
// 12345
println(data["due"]!)
// due date
println(data["description"]!)
// some description

编辑:添加问题的解决方案。问题在于 JSON 结果的投射方式。而不是作为? NSDictionary 用作? [任何对象]

let serverJsonResponse = "[{\"id\":\"284ad166f8152268e4010c4cb21c40c13f195165\",\"due\":null,\"description\":\"\",\"status\":\"LATE\",\"summary\":\"tache late\",\"context\":\"\",\"folder\":\"INBOX\"},{\"id\":\"b43bd766295220b23279899d025217d18e98374a\",\"due\":null,\"description\":\"\",\"status\":\"IN-PROCESS\",\"summary\":\"tache in process\",\"context\":\"\",\"folder\":\"INBOX\"}]"

var error: NSError?

let json/*: [AnyObject]*/ = NSJSONSerialization.JSONObjectWithData(serverJsonResponse.dataUsingEncoding(NSUTF8StringEncoding)!, options: NSJSONReadingOptions.MutableContainers, error: &error) as [AnyObject]

// println(json)

// Before casting to [AnyObject]
// println(json as? [AnyObject])

// dump(json)

for dict in json {
    // dump(dict)

    println(dict["id"])
    println(dict["due"])
    println(dict["description"])

    // if let id = dict["id"] as? Int {
       // println(id)
    // }

    // if let due = dict["due"] as? String {
        // println(due)
    // }

    // if let description = dict["description"] {
        // println(description)
    // }
}

【讨论】:

【解决方案2】:

如果您实际上将其作为 NSDictionary 取回,则无需将其转换为其他任何内容。

var responseDict = json!.objectForKey("data") as! NSDictionary
var idString = responseDict.objectForKey("id") as! String
var dueString = responseDict.objectForKey("due") as! String

【讨论】:

  • 感谢您的回答。我在第一行有一条错误消息:Could not cast value of type '__NSCFString' (0xd417ac) to 'NSDictionary' (0xd41d74). json is declared as NSDictionnary?这是他的价值:value __NSCFString *@"[{\"id\":\"284ad166f8152268e4010c4cb21c40c13f195165\",\"due\":null,\"description\":\"\",\"status\":\"LATE\",\"summary\":\"tache late\",\"context\":\"\",\"folder\":\"INBOX\"},{\"id\":\"b43bd766295220b23279899d025217d18e98374a\",\"due\":null,\"description\":\"\",\"status\":\"IN-PROCESS\",\"summary\":\"tache in process\",\"context\":\"\",\"folder\":\"INBOX\"}]"
【解决方案3】:

响应中的 JSON data 字段是一个字典数组([ 是 JSON 数组的起始分隔符,{ 是 JSON 字典的起始分隔符)。

[{\"id\":\"284ad166f8152268e4010c4cb21c40c13f195165\",\"due\":null,\"descript‌​ion\":\"\",\"status\":\"LATE\", \"summary\":\"tache late\",\"context\":\"\",\"folder\":\"INBOX\"},{\"id\": ...

因此,一旦您使用现有行解码了全局 JSON 响应:

let json = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &err) as? NSDictionary

您只需要像@iosDev82 解释的那样获取响应的这一部分,但是您必须将其转换为字典数组而不是简单的字典:

if let responseArray = json!.objectForKey("data") as? [[String:AnyObject]] {
    for dic in responseArray {
        let theID = dic["id"] as? String
        let theStatus = dic["status"] as? String
        // etc
    }
}

编辑:

嗯,我知道你的数据让我想起了一些事情......看看这个:https://stackoverflow.com/a/30570819/2227743我已经向你解释了这个问题。 :)

您必须首先将data 字段视为字符串,然后解码它包含的 JSON,然后访问它的对象。

解码 JSON 响应 > 将“数据”字段作为字符串 > 解码 this JSON 字符串 > 访问对象

例子:

let dataFieldDecodedFromJSONAsString = "[{\"id\":\"284ad166f8152268e4010c4cb21c40c13f195165\",\"due\":null,\"description\":\"\",\"status\":\"LATE\",\"summary\":\"tache late\",\"context\":\"\",\"folder\":\"INBOX\"},{\"id\":\"b43bd766295220b23279899d025217d18e98374a\",\"due\":null,\"description\":\"\",\"status\":\"IN-PROCESS\",\"summary\":\"tache in process\",\"context\":\"\",\"folder\":\"INBOX\"}]"
let insideJSONStringReEncodedAsData = dataFieldDecodedFromJSONAsString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
if let json2 = NSJSONSerialization.JSONObjectWithData(insideJSONStringReEncodedAsData!, options: nil, error: nil) {
    if let responseArray = json2 as? [[String:AnyObject]] {
        for dic in responseArray {
            let theID = dic["id"] as? String
            let theStatus = dic["status"] as? String
            // etc
        }
    }
}

【讨论】:

  • 谢谢,你帮助我理解了这个 JSON 是什么。但我很惊讶,我没有进入 if 条件,一旦他强调了条件,就会逐步退出 if
猜你喜欢
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
相关资源
最近更新 更多