首页 > 解决方案 > 如何快速将对象转换为可序列化的 JSON

问题描述

我是那种在屏蔽时搜索网络的类型,但现在我无法找到或理解。

我必须对 API 做一个简单的发布,但我不能在我的请求参数中传递我的对象。

当我用测试测试我的 var 参数时let checker = JSONSerialization.isValidJSONObject(parameters),它仍然是错误的。

我必须将此变量“参数”作为请求的 httpBody 传递 guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}

    
    let userId: String
    let listItems: [ListItem]
    
    internal init(userId: String, listItems: [ListItem] = []) {
        self.userId = userId
        self.listItems = listItems
    }
    
    enum CodingKeys: String, CodingKey {
        case userId
        case listItems
    }
}

// MARK: - ListItem
struct ListItem: Codable {
    internal init(nameDrug: String, code_cip: String, unitStock: Double) {
        self.nameItem = nameItem
        self.code_cip = code_cip
        self.unitStock = unitStock
    }
    
    let nameItem, code_cip: String
    let unitStock: Double

    enum CodingKeys: String, CodingKey {
        case nameItem
        case code_cip
        case unitStock
    }
    
}```


The API expects a body under this structure

```    {
        "userId":"60c0ede9dfc16e46e45b026buh4vyw8",
        "listItems":
                [
                {"nameItem":"Random name item 1","code_cip":"34009275623967319","unitStock":17},
                {"nameItem":"Random name item 2","code_cip":"34009300409352486","unitStock":17}
                ]
    }

对不起我的英语,这不是我的母语,谢谢你的帮助;)

标签: jsonswiftapirequestjson-serialization

解决方案


我认为 JSONSerialization 需要字典或数组作为顶级对象。

请改用 JSONEncoder。

https://developer.apple.com/documentation/foundation/jsonencoder


推荐阅读