在Swift,AnyObject类型中解析json

时间:2014-07-10 07:57:31

标签: json parsing swift

我正在尝试解析json但是我对数据类型有一些困难,特别是AnyObject类型+向下转换。

让我们考虑下面的json(它是一个完整的json的摘录)。

{  "weather":
   [
      {
         "id":804,
         "main":"Clouds",
         "description":"overcast clouds",
         "icon":"04d"
      }
   ],
}

对我来说,json可以描述如下:

- json: Dictionary of type [String: AnyObject] (or NSDictionary, so = [NSObject, AnyObject] in Xcode 6 b3)
    - "weather": Array of type [AnyObject] (or NSArray)
         - Dictionary of type [String: AnyObject] (or NSDictionary, so = [NSObject, AnyObject] in Xcode 6 b3)

我的json是AnyObject类型! (我使用JSONObjectWithData从URL获取JSON。)

然后我想访问天气词典。这是我写的代码。

var localError: NSError?
var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &localError)

if let dict = json as? [String: AnyObject] {
 if let weatherDictionary = dict["weather"] as? [AnyObject] {
      // Do stuff with the weatherDictionary
    }
}

这是我得到的错误

Playground execution failed: error: <EXPR>:28:56: error: '[AnyObject]' is not a subtype of '(String, AnyObject)'
        if let weatherDictionary = dict["weather"] as? [AnyObject] {

我不明白为什么将dict [“weather”]与(String,AnyObject)的子类型而不是AnyObject进行比较。

我将我的字典声明为[String:AnyObject],所以我使用String键访问一个值,我应该有一个AnyObject,不是吗?

如果我使用NSDictionary而不是[String:AnyObject],它可以工作。

如果我使用NSArray而不是[AnyObject],它可以工作。

- The Xcode 6 beta 3 release notes tell that "NSDictionary* is now imported from Objective-C APIs as [NSObject : AnyObject].".
- And the Swift book: "When you bridge from an NSArray object to a Swift array, the resulting array is of type [AnyObject]."

修改

我忘了强行解开字典[“天气”]!。

if let dict = json as? [String: AnyObject] {
    println(dict)
       if let weatherDictionary = dict["weather"]! as? [AnyObject] {
            println("\nWeather dictionary:\n\n\(weatherDictionary)")
            if let descriptionString = weatherDictionary[0]["description"]! as? String {
                println("\nDescription of the weather is: \(descriptionString)")
        }
    }
}

请注意,我们应该仔细检查是否存在第一个Optional。

if let dict = json as? [String: AnyObject] {
    for key in ["weather", "traffic"] {
        if let dictValue = dict[key] {
            if let subArray = dictValue as? [AnyObject] {
                println(subArray[0])
            }
        } else {
            println("Key '\(key)' not found")
        }
    }
}

3 个答案:

答案 0 :(得分:35)

使用env xcrun swift

,这对我在游乐场和终端中运行良好

更新为SWIFT 4和CODABLE

这是使用Codable协议的Swift 4示例。

var jsonStr = "{\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],}"

struct Weather: Codable {
    let id: Int
    let main: String
    let description: String
    let icon: String
}

struct Result: Codable {
    let weather: [Weather]
}

do {
    let weather = try JSONDecoder().decode(Result.self, from: jsonStr.data(using: .utf8)!)
    print(weather)
}
catch {
    print(error)
}

SWIFT 3.0更新

我已经更新了Swift 3的代码,并展示了如何将解析后的JSON包装到对象中。感谢所有的投票!

import Foundation

struct Weather {
    let id: Int
    let main: String
    let description: String
    let icon: String
}

extension Weather {
    init?(json: [String: Any]) {
        guard
            let id = json["id"] as? Int,
            let main = json["main"] as? String,
            let description = json["description"] as? String,
            let icon = json["icon"] as? String
        else { return nil }
        self.id = id
        self.main = main
        self.description = description
        self.icon = icon
    }
}

var jsonStr = "{\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],}"

enum JSONParseError: Error {
    case notADictionary
    case missingWeatherObjects
}

var data = jsonStr.data(using: String.Encoding.ascii, allowLossyConversion: false)
do {
    var json = try JSONSerialization.jsonObject(with: data!, options: [])
    guard let dict = json as? [String: Any] else { throw JSONParseError.notADictionary }
    guard let weatherJSON = dict["weather"] as? [[String: Any]] else { throw JSONParseError.missingWeatherObjects }
    let weather = weatherJSON.flatMap(Weather.init)
    print(weather)
}
catch {
    print(error)
}

- 上一个答案 -

import Foundation

var jsonStr = "{\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],}"
var data = jsonStr.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
var localError: NSError?
var json: AnyObject! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &localError)

if let dict = json as? [String: AnyObject] {
    if let weather = dict["weather"] as? [AnyObject] {
        for dict2 in weather {
            let id = dict2["id"]
            let main = dict2["main"]
            let description = dict2["description"]
            println(id)
            println(main)
            println(description)
        }
    }
}

由于我仍在为这个答案获得投票,我想我会为Swift 2.0重新审视它:

import Foundation

var jsonStr = "{\"weather\":[{\"id\":804,\"main\":\"Clouds\",\"description\":\"overcast clouds\",\"icon\":\"04d\"}],}"
var data = jsonStr.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: false)
do {
    var json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)

    if let dict = json as? [String: AnyObject] {
        if let weather = dict["weather"] as? [AnyObject] {
            for dict2 in weather {
                let id = dict2["id"] as? Int
                let main = dict2["main"] as? String
                let description = dict2["description"] as? String
                print(id)
                print(main)
                print(description)
            }
        }
    }

}
catch {
    print(error)
}

最大的区别是变量json不再是可选类型和do / try / catch语法。我也继续输入idmaindescription

答案 1 :(得分:6)

尝试:

有了它,你可以这样:

let obj:[String:AnyObject] = [
    "array": [JSON.null, false, 0, "", [], [:]],
    "object":[
        "null":   JSON.null,
        "bool":   true,
        "int":    42,
        "double": 3.141592653589793,
        "string": "a α\t弾\n",
        "array":  [],
        "object": [:]
    ],
    "url":"http://blog.livedoor.com/dankogai/"
]

let json = JSON(obj)

json.toString()
json["object"]["null"].asNull       // NSNull()
json["object"]["bool"].asBool       // true
json["object"]["int"].asInt         // 42
json["object"]["double"].asDouble   // 3.141592653589793
json["object"]["string"].asString   // "a α\t弾\n"
json["array"][0].asNull             // NSNull()
json["array"][1].asBool             // false
json["array"][2].asInt              // 0
json["array"][3].asString           // ""

答案 2 :(得分:4)

使用我的库(https://github.com/isair/JSONHelper),您可以使用AnyObject类型的 json 变量执行此操作:

var weathers = [Weather]() // If deserialization fails, JSONHelper just keeps the old value in a non-optional variable. This lets you assign default values like this.

if let jsonDictionary = json as? JSONDictionary { // JSONDictionary is an alias for [String: AnyObject]
  weathers <-- jsonDictionary["weather"]
}

如果您的阵列没有在密钥&#34;天气&#34;下,您的代码就是这样:

var weathers = [Weather]()
weathers <-- json

或者如果你手中有一个json字符串,你也可以传递它,而不是先从字符串创建一个JSON字典。您需要做的唯一设置是编写Weather类或结构:

struct Weather: Deserializable {
  var id: String?
  var name: String?
  var description: String?
  var icon: String?

  init(data: [String: AnyObject]) {
    id <-- data["id"]
    name <-- data["name"]
    description <-- data["description"]
    icon <-- data["icon"]
  }
}