首页 > 解决方案 > 将来自 JSON 字典字典的 http 请求中的数据转换为 Swift 中的一个字典数组

问题描述

运行我的 http 请求时,我以下列方式返回数据。

我要求如下

    do {
        if let file = URL(string: "https://myhttprequest....") {
            let data = try Data(contentsOf: file)
            let json = try JSONSerialization.jsonObject(with: data, options: [])
            if let object = json as? [String: Any] {
                // json is a dictionary
                print(object)
            } else {
                print("JSON is invalid")
            }
        } else {
            print("no file")
        }
    } catch {
        print(error.localizedDescription)
    }

例如,http 请求显示如下

{"created":[{"id":"-LVEAdIk2KwDmxBj25pK","caption":"Cool watch bro ","creationDate":1546442937.5934439,"imageHeight":1000,"imageUrl":"https://firebasestorage.googleapis.com/..."}],"reshared":[{"id":"-LVEAdIk2KwDmxBj25pK","caption":"Cool watch bro ","creationDate":1546442937.5934439,"imageHeight":1000,"imageUrl":"https://firebasestorage.googleapis.com/..."}]}

我希望能够将 object["created"] 和 object["reshared"] 的值放在一起,得到一个由两个字典组成的数组 [[caption:"", creationDate:""...],[caption: ““, 创建日期:””...]]

我尝试过像 object["created"] 一样单独访问它们,但它不是字典类型,我似乎无法弄清楚如何让它成为一个。

更新:所以我现在正在做以下守卫 let uid = Auth.auth().currentUser?.uid else { return }

    let url = URL(string: "https://us-central1-flashtrend-bdcd3.cloudfunctions.net/getFeed/\(uid)")!

    let task = URLSession.shared.dataTask(with: url) {(data, response, error) in
        guard let firstData = data else { return }
        let jsonStr = String(data: firstData, encoding: .utf8)!
        guard  let data = jsonStr.data(using: .utf8) else {
            return
        }
        do {
            guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
                return
            }
            guard let created = json["created"], let reshared = json["reshared"] else {
                return
            }
            let result = [created, reshared]

            print(result)

        } catch  {
            print(error.localizedDescription)
        }
    }

    task.resume()

但是当我打印时它看起来很奇怪

[<__NSSingleObjectArrayI 0x600002de2290>(
{
    caption = "Cool watch bro ";
    creationDate = "1546442937.593444";
    id = "-LVEAdIk2KwDmxBj25pK";
    imageHeight = 1000;
    imageUrl = "https://firebasestorage.googleapis.com/v0/b/flashtrend-bdcd3.appspot.com/o/posts%2FE346E4B7-31D8-4E9E-89F2-DA7C426C0537?alt=media&token=4936ce58-64bb-4d5a-b913-c3b87705614f";
    imageWidth = 750;
    swipes = 0;
    userid = U9097gARoXOus96vT1uBHAcNPs03;
    views = 1;
}
)
, <__NSArray0 0x600002df40c0>(

)
] 

标签: iosarraysjsonswiftdictionary

解决方案


我已将 http 请求结果更改为json string,您的示例代码如下,在我的 xcode 上运行良好:

let jsonStr = "{\"created\":{\"caption\":\"Cool watch bro \",\"creationDate\":\"1546442937.593444\",\"id\":\"-LVEAdIk2KwDmxBj25pK\",\"imageHeight\":1000,\"imageUrl\":\"https://firebasestorage.googleapis.com/v0/b/flashtrend-bdcd3.appspot.com/o/posts/E346E4B7-31D8-4E9E-89F2-DA7C426C0537?alt:media&token:4936ce58-64bb-4d5a-b913-c3b87705614f\",\"imageWidth\":750,\"swipes\":0,\"userid\":\"U9097gARoXOus96vT1uBHAcNPs03\",\"views\":1},\"reshared\":{\"caption \":\"Cool watch bro\",\"creationDate \":\"1546442937.593444\",\"id \":\"-LVEAdIk2KwDmxBj25pK \",\"imageHeight\":1000,\"imageUrl\":\"https://firebasestorage.googleapis.com/v0/b/flashtrend-bdcd3.appspot.com/o/posts/E346E4B7-31D8-4E9E-89F2-DA7C426C0537?alt:media&token:4936ce58-64bb-4d5a-b913-c3b87705614f\",\"imageWidth\":750,\"swipes\":0,\"userid\":\"U9097gARoXOus96vT1uBHAcNPs03\",\"views\":1}}"

guard  let data = jsonStr.data(using: .utf8) else {
    return
}
do {
    guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
        return
    }
    guard let created = json["created"], let reshared = json["reshared"] else {
        return
    }
    let result = [created, reshared]
    print(result)
} catch  {
    print(error.localizedDescription)
}

推荐阅读