我目前正在向后端发送一系列字典,如下所示-
"args": [
{
"mobileData" = {
"accessState" = 1;
"changeState" = 0;
};
},
{
"bluetooth" = {
"accessState" = 1;
"changeState" = 0;
};
}]
我使用Swift4 Codable协议对它们进行编码/解码,并且效果很好。
但是,后端希望整个args
作为对象(字典),其中包含所有其他KVP(例如mobileData,蓝牙等),如下所示-
"args":{
"mobileData":{
"accessState":1,
"changeState":0
},
"bluetooth" = {
"accessState" = 1;
"changeState" = 0;
};
}
不确定如何使用Swift Codable协议创建类似的内容而无需将“ args”内的“ values”设置为字符串。任何帮助,将不胜感激。我缺少明显的东西吗?
答案 0 :(得分:0)
每个字典都由一个结构表示。像这样:
struct States:Encodable {
let accessState:Int
let changeState:Int
}
struct Args:Encodable {
let mobileData:States
let bluetooth:States
}
struct Wrapper:Encodable {
let args:Args
}
let json = Wrapper(
args: Args(
mobileData: States(accessState: 1, changeState: 0),
bluetooth: States(accessState: 1, changeState: 0)
)
)
let data = JSONEncoder().encode(json)
print(String(data: data, encoding: .utf8)!)
// {"args":{"mobileData":{"accessState":1,"changeState":0},"bluetooth":{"accessState":1,"changeState":0}}}