如何将对象的json转换为字典 [英] How to convert a json of objects to dictionary

查看:129
本文介绍了如何将对象的json转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的json:

I have a json like this :

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

现在我想将其转换成这样的字典:

now I would like to convert it to a dictionary like this :

key:value

在这种情况下,

是任意的(唯一的Int),而value是对象.

in this case the key is arbitrary (an unique Int) and value is objects.

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

I wanted to use this function but it returns 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答案,但出现错误:

I want to use @Nirav D answer but I got an error :

   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? []

推荐答案

您有JSON响应,顶级为Array而不是dictionary.因此,您需要将其强制转换为[[String:Any]]而不是[String: Any].

You have JSON response with Top level as Array not dictionary. So you need to cast it to [[String:Any]] instead of [String: Any].

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

Now if you want to convert this Array response to Dictionary with type [Int:Any] then you need to loop through the array and make dictionary from it.

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

这篇关于如何将对象的json转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆