web-dev-qa-db-fra.com

Parse json dans Swift, type AnyObject

J'essaie d'analyser un json mais j'ai quelques difficultés avec les types de données et notamment avec le type AnyObject + downcasting.

Considérons le JSON suivant (c'est un extrait d'un JSON complet).

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

Pour moi, le JSON peut être décrit comme suit:

- 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)

Mon json est de type AnyObject! (J'utilise JSONObjectWithData pour obtenir le JSON à partir d'une URL).

Je veux ensuite accéder au dictionnaire météo. Voici le code que j'ai écrit.

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
    }
}

Voici l'erreur que j'ai eu

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

Je ne comprends pas pourquoi dict ["weather"] est comparé à un sous-type de (String, AnyObject) et non à AnyObject.

J'ai déclaré mon dictionnaire comme étant [String: AnyObject], alors j'accède à une valeur à l'aide de la clé String, je devrais avoir un AnyObject, non?

Si j'utilise NSDictionary au lieu de [String: AnyObject], cela fonctionne.

Si j'utilise NSArray au lieu de [AnyObject], cela fonctionne.

- 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]."

EDIT

J'ai oublié de forcer le démantèlement du dict ["temps"] !.

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)")
        }
    }
}

Notez que nous devrions vérifier l'existence du premier facultatif.

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")
        }
    }
}
39
alpennec

Cela fonctionne bien pour moi dans la cour de récréation et dans le terminal en utilisant env xcrun Swift

MIS À JOUR POUR Swift 4 ET CODABLE

Voici un exemple Swift 4 utilisant le protocole Codable.

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)
}

MIS À JOUR POUR Swift 3.0

J'ai mis à jour le code pour Swift 3 et j'ai également montré comment envelopper le JSON analysé dans des objets. Merci pour tous les votes positifs!

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)
}

- Réponse précédente -

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)
        }
    }
}

Comme je reçois toujours des votes positifs pour cette réponse, j'ai décidé de la revoir pour 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)
}

La plus grande différence est que la variable json n'est plus un type optionnel et la syntaxe do/try/catch. Je suis aussi allé de l'avant et ai tapé id, main et description.

35
Daniel T.

Essayer:

Avec ça tu peux aller comme ça:

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           // ""
6
dankogai

En utilisant ma bibliothèque ( https://github.com/isair/JSONHelper ), vous pouvez le faire avec votre variable json de tapez AnyObject:

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"]
}

Si votre tableau n’avait pas été placé sous la clé "météo", votre code aurait été juste ceci:

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

Ou si vous avez une chaîne JSON entre vos mains, vous pouvez également la transmettre, au lieu de créer un dictionnaire JSON à partir de la chaîne. La seule configuration à faire est d’écrire une classe ou une structure 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"]
  }
}
4
isair