我从Web服务接收JSON字典,我需要将返回值映射到现有值。这基本上就是我想要做的事情:
class Contract {
var contractID: String?
var ebState: String?
var ibState: String?
var importerState: String?
var exportersBankRefNo: String?
var importersBankRefNo: String?
}
let contract1 = Contract()
contract1.contractID = "001"
let contract2 = Contract()
contract2.contractID = "002"
// This is the JSON return dictionary
let exportAppnStatusList: [[String: String]] = [["contractID":"001",
"ExporterBankRefNo":"ExporterBankRefNo001",
"ExporterBankState":"ACCEPTED",
"ImporterBankRefNo":"",
"ImporterBankState":"UNKNOWN",
"ImporterState":"UNKNOWN" ],
["contractID":"002",
"ExporterBankRefNo":"ExporterBankRefNo002",
"ExporterBankState":"ACCEPTED",
"ImporterBankRefNo":"ImporterBankRefNo002",
"ImporterBankState":"ACCEPTED",
"ImporterState":"UNKNOWN" ]]
我需要使用exportAppnStatusList
并填写现有contract1
和contract2
中的关联值,并按contractID
答案 0 :(得分:3)
这会使合同中包含可用信息,它会忽略无法找到ID的合同:
for contract in [contract1, contract2] {
if let contractDict = exportAppnStatusList.filter({$0["contractID"] == contract.contractID}).first {
contract.exportersBankRefNo = contractDict["ExporterBankRefNo"]
contract.ebState = contractDict["ExporterBankState"]
contract.importersBankRefNo = contractDict["ImporterBankRefNo"]
contract.ibState = contractDict["ImporterBankState"]
contract.importerState = contractDict["ImporterState"]
}
}
答案 1 :(得分:0)
尝试使用此init(您的类必须从NSObject继承):
init(jsonDict: [String: String]) {
super.init()
for (key, value) in jsonDict {
if class_respondsToSelector(Contract.self, NSSelectorFromString(key)) {
setValue(value, forKey: key)
}
}
}
然后你可以这样做:
exportAppnStatusList.forEach {
print(Contract(jsonDict: $0))
}
答案 2 :(得分:0)
为什么不通过映射这样的字典数组来生成合约对象?您需要编写一个自定义初始化程序来获取所有这些参数
string sourceDirectory = @"C:\TestInput\";
string destinationDirectory = @"C:\TestOutput\";
// or with OpenFileDialog.FileNames
string[] inputFiles = System.IO.Directory.GetFiles(sourceDirectory)
foreach(string inputfilePath in inputFiles)
{
string outputfilePath = System.IO.Path.Combine(destinationDirectory,
System.IO.Path.GetFileName(inputfilePath) + "_encrypted");
//Encrypt here
}