如何将json对象转换为字典

时间:2017-02-21 08:57:18

标签: json swift dictionary

我有一个像这样的json:

[
  {
    "id" : 887,
    "title" : "ماه نو",
    "voice_actor" : "ع. پاشایی",
    "compiler" : "رابیندرانات تاگور",
    "cover_image" : "d5c446a1d81340d2bb912d51b00a3d79"
  },
  {
    "id" : 607,
    "title" : "حکایت آن که دلسرد نشد (درس هایی برای رسیدن به موفقیت و ثروت)",
    "voice_actor" : "حمید محمدی",
    "compiler" : "مارک فیشر",
    "cover_image" : "26ead648b33e4977805c7e979f8cc78c"
  }
]

现在我想把它转换成这样的字典:

key:value

在这种情况下,key是任意的(唯一的Int),value是对象。

我想使用此功能,但它返回nil:

 func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
            } catch {
                print(error.localizedDescription)
            }
        }    

 let value = self.convertToDictionary(text: abovejson)
 //value is null

更新

我想使用@Nirav D答案,但我收到了一个错误:

   func convertToDictionary(text: String) -> [String: Any]? {
        if let data = text.data(using: .utf8) {
            do {
                let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] as? []
                var dictionary = [Int:Any]()
                //Loop through array and set object in dictionary
                for (index,item) in array.enumerated() {
                    let uniqueID = index //Or generate uniqued Int id
                    dictionary[uniqueID] = item
                }
            }
            catch {}
        }
        return nil
    }


Expected element type for as? []

enter image description here

3 个答案:

答案 0 :(得分:2)

您的最高级别JSON回复为Array而不是dictionary。因此,您需要将其投放到[[String:Any]]而不是[String: Any]

现在,如果您想将此Array响应转换为Dictionary类型[Int:Any],则需要循环遍历数组并从中创建字典。

do {
     let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String: Any]] ?? []
     var dictionary = [Int:Any]()
     //Loop through array and set object in dictionary
     for (index,item) in array.enumerated() {
         let uniqueID = index //Or generate uniqued Int id 
         dictionary[uniqueID] = item
     }
}
catch {}

答案 1 :(得分:0)

我建议使用SwiftyJSON,这样可以在Swift中轻松转换和访问JSON数据。

// A Simple sample
let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
  //Now you got your value
}

https://github.com/SwiftyJSON/SwiftyJSON

答案 2 :(得分:-1)

func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
    do {
        return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
    } catch {
        print(error.localizedDescription)
    }
}
return nil

}

让str =“{\”name \“:\”James \“}”

让dict = convertToDictionary(text:str)

swift 2

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
    do {
        return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]
    } catch let error as NSError {
        print(error)
    }
}
return nil
 }

 let str = "{\"name\":\"James\"}"

  let result = convertStringToDictionary(str)