2016-12-09 7 views
1

Ich schreibe einen Code in Swift 3 für eine Abfrage im JSON-Format Ergebnis von http Anfrage.SwiftyJSON parsen json Abfrage

JSON-Format ist:

JSON: { 
base = stations; 
coord =  { 
    lat = "23.9"; 
    lon = "42.89"; 
}; 
weather =  (
      { 
     description = mist; 
     icon = 50n; 
     id = 701; 
     main = Mist; 
    }, 
      { 
     description = fog; 
     icon = 50n; 
     id = 741; 
     main = Fog; 
    } 
); 
wind =  { 
    deg = "222.506"; 
    speed = "1.72"; 
};} 

Mein Code ist:

Alamofire.request(url).responseJSON { response in 

     if let a = response.result.value { 

      let jsonVar = JSON(a) 

      if let resDati = jsonVar["base"].string { 
       print(resDati as String) // <- OK 
      } 

      if let dati2 = jsonVar["weather"].array { 

       for item in dati2 { 

        print(" > \(item["main"])") // <- OK 

       } 

      } 

     } else { 
      print(Error.self) 
     } 

    } 

Das Problem auf "coord" und "Wind" Daten Ich habe try:

if let dati4 = jsonVar["wind"].array { 

    for item in dati4 { 

     print("-- \(item)") 

    } } 

Ich kann die Daten Verwandten nicht im JSON-Format "wind" und "koordinieren".

Wie kann ich das beheben?

Vielen Dank.

Antwort

2

Der Schlüssel wind ein Wörterbuch enthält, nicht ein Array ist, können Sie die deg und speed Werte mit SwiftyJSON mit diesem Code erhalten:

if let wind = jsonVar["wind"].dictionary, 
    let deg = wind["deg"]?.double, 
    let speed = wind["speed"]?.double { 
    print(deg, speed) 
} 

coord Werke

if let coord = jsonVar["coord"].dictionary, 
    let lat = coord["lat"]?.double, 
    let lon = coord["lon"]?.double { 
    print(lat, lon) 
} 

Hinweis entsprechend: Alle Werte sind vom Typ Double, das JSON-Format ist irreführend.

+0

Ich schreibe Ihren Code, aber das Ergebnis von 'deg' und 'Geschwindigkeit' ist Null. –

+0

Wenn 'jsonVar [" base "]' etwas ausgibt ('<- OK'), soll mein Code funktionieren. auch. – vadian

+0

Ich habe Ihren Code bei mir und in der Konsole hinzugefügt es die 'Basis' und das 'Wetter', aber nicht 'Wind', so habe ich shift 'Let deg' und 'lass Geschwindigkeit' von 'if' und in der Konsole sehe ich "Nil Nil". –