您好我在sqlite表中存储实时api数据,之后我在用户打开互联网时再次检索我在字符串中成功检索但后来我想在json数组中转换该数据,如下所示
预期产出
[{"properties_id":"1234","house_number":"1"},{"properties_id":"1234","house_number":"2"}]
我试图转换我会告诉你我试过的代码,但我得到错误的输出如下
OutPut我得到了
[["17", "1", "1234"], ["18", "2", "1234"]]
这是我的代码
var mainLocalArray = [Any]()
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") as! ProjectsTableViewCell
let name = propertyLocalData[indexPath.row].house_number
cell.lblProjectsName.text = "\(name!)"
cell.viewVisitView.backgroundColor = UIColor(red: 86/255, green: 35/255, blue: 127/255, alpha: 1)
let id = propertyLocalData[indexPath.row].id
let pro_ID = propertyLocalData[indexPath.row].proID
let housnumber = propertyLocalData[indexPath.row].house_number
let arrayLocal = ["\(id)", "\(pro_ID)", housnumber!] as [Any]
print(arrayLocal)
self.mainLocalArray.append(arrayLocal)
print(mainLocalArray)
return cell
}
我正在创建数组的数组,我从数据库获得并附加到其他mainlocalarray但如何转换为json数组无法理解请帮助某人。
cellForRowAt
绝对是转换数据的错误地方。
使用Encodable
协议的简单解决方案
var mainLocalArray = [Any]()
let arrayLocal = ["\(id)", "\(pro_ID)", housnumber!] as [Any]
print(arrayLocal)
self.mainLocalArray.append(arrayLocal)
print(mainLocalArray)
propertyLocalData
的类型)添加Encodable
和CodingKeys
struct MyStruct : Encodable {
...
private enum CodingKeys : String, CodingKey { case id = "properties_id", house_number }
... }
cellForRow
中)编码数据源数组
do {
let jsonData = try JSONEncoder().encode(propertyLocalData)
let jsonString = String(data: jsonData, encoding: .utf8)!
print(jsonString)
} catch { print(error) }
PS:删除SwiftyJSON。