如何快速将对象转换为可序列化的 JSON

问题描述

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

我必须向 API 发送一个简单的帖子,但我无法在请求的参数中传递我的对象。

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

我必须将此变量“参数”作为我请求的 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}
                ]
    }

对不起,我的英语不是我的母语,感谢您的帮助;)

解决方法

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

改用 JSONEncoder。

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

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...