Kuroiteiken
Kuroiteiken

Reputation: 308

Json Parsing at Swift with alamofire

I'm parsing JSON with alamofire in swift. I'm trying to look loop my json but there is something wrong with my code. When looking through code with debugger, my application wont enter at if and for. Whats wrong with my code? I have to loop my json with "for" and parse my json data.

    Alamofire.request(apiToContact, method: .get, encoding: URLEncoding.default, headers: headersq).responseJSON { (response) in
    print(response)
    if response.result.isSuccess {

        guard let resJson = response.result.value else { return }

        print(resJson);
        if let json = response.result.value as? [String:AnyObject] {
            for entry in json {
                print("\(entry)") // this is where everything crashes
            }
        }

     if let JSON = response.result.value as? NSDictionary{
            for entry in JSON {
                print("\(entry)") // this is where everything crashes
            }
        }

    }
    if response.result.isFailure {

    }
}

Print(response) gives this json.:

    SUCCESS: (
    {
        KoorX = "38.414745";
        KoorY = "27.183055";
        Yon = 1;
    },
    {
        KoorX = "38.41474";
        KoorY = "27.18382667";
        Yon = 1;
    },
    {
       KoorX = "38.422255";
       KoorY = "27.15055167";
       Yon = 1;
}

)

Upvotes: 0

Views: 96

Answers (2)

Indian Rythu bidda
Indian Rythu bidda

Reputation: 128

This Code Help You

if let locationJSON = response.result.value
     {
      let locationObject: Dictionary = locationJSON as! Dictionary<String, Any>
       self.dataArray = locationObject["data"]as! NSArray

        }

Upvotes: 0

vadian
vadian

Reputation: 285069

First of all in Swift 3+ a JSON dictionary is [String:Any]

Two issues:

  1. The array is the value for key SUCCESS in the root object.
  2. The fast enumeration syntax for a dictionary is for (key, value) in dictionary

guard let resJson = response.result.value as? [String:Any],
      let success = resJson["SUCCESS"] as? [[String:Any]] else { return }
      for entry in success {
            print(entry)
        }
    } 

Upvotes: 1

Related Questions