【问题标题】:How to append data to a JSON value of type array in swift 4如何在swift 4中将数据附加到数组类型的JSON值
【发布时间】:2018-10-15 03:29:31
【问题描述】:

这是我的 json 对象代码。我正在尝试将图像字典放入图像值中。我已经尝试了很多东西,也许我错过了一些东西。

 let jsonObject: [String: Any] = [
        "name_space": "users",
        "data_collection": "data://brownfosman5000/DatFace/",
        "action" : "add_images",
        "images": []
    ]

我创建了一个 json 字典来保存图像

let imageDictionary = try! JSONSerialization.jsonObject(with: imageJSON, options: []) as! [String : Any]

我还创建了一个数组来保存 imageDictionaries 数组

let images:NSMutableArray = NSMutableArray()
self.images.add(imageDictionary)

如何将图像数组作为字典添加到我的 json 数组中? 一切都很好,我只需要将它添加到 json 中。

【问题讨论】:

    标签: json swift4 swifty-json algorithmia


    【解决方案1】:

    首先,不要在 Swift 中使用 NSMutable... 集合类型。使用带有 var 关键字的原生类型

    var images = [[String:Any]]()
    

    第二个使jsonObject 也可变

    var jsonObject: [String: Any] = [ ...
    

    将字典追加到images

    images.append(imageDictionary)
    

    将数组分配给关键字images的字典

    jsonObject["images"] = images
    

    【讨论】:

    • 感谢这帮助我将数据发送到我的 api!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-30
    • 2021-09-28
    • 1970-01-01
    • 2020-01-14
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多