-3

I get json like this from the server:

array('id' => '1', 'name' => 'Radni nalog 1', 'threadTypeList' => array(
            array('id' => '1', 'name' => 'Crvena'), 
            array('id' => '2', 'name' => 'Plava'), 
            array('id' => '3', 'name' => 'Zelena'), 
            array('id' => '4', 'name' => 'Žuta'), 
        ), 'token' => 'xxuoE73VKwyKk1KmGTy26P72cgsuneMzNOes');

How can I convert this json to the dictionary. Here is my function for conversion, but it is totally wrong and I am stuck with it.

func convertStringToDictionary2(text: String) -> [AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [AnyObject]
            return json
        } catch {
            print("Something went wrong")
        }
    }
    return nil
}

and when I try to get data like this:

    let result = convertStringToDictionary(jsonString as String)

//creating array of objects threadType and populating threadTypeList property
let resultThreadList = (result?["threadTypeList"] as! String)

let new = convertStringToDictionary2(resultThreadList as String)

I get an error: Could not cast value of type '__NSArrayI' (0x10f20dd88) to 'NSString' (0x10df90c40).

I am able to get all the variables from json except ** threadTypeList** which is an array of arrays.

1 Answers1

0

The error

Could not cast value of type '__NSArrayI' (0x10f20dd88) to 'NSString' (0x10df90c40)

means:

The object you are going to access is Array but you want to get a String which is impossible.

let resultThreadList = result?["threadTypeList"] as! [[String:AnyObject]]

resultThreadList implies an array as well as the PHP type 'threadTypeList' => array( but consider that a PHP (associative) array array('id' => '1' is actually a dictionary.

vadian
  • 274,689
  • 30
  • 353
  • 361