0

Hello I am storing live api data in sqlite table and after that I am retrieving again when user turn on internet I retrieving successfully in string but then i want to convert that data in json array like below

Expected Output

[{"properties_id":"1234","house_number":"1"},{"properties_id":"1234","house_number":"2"}]

i have tried to convert i will show you code which i tried but i am getting wrong output like below

OutPut Which i get

[["17", "1", "1234"], ["18", "2", "1234"]]

Here is my Code

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
    }

I am creating array of values which I get from data base and appending in other mainlocalarray but how to convert in json array not able to understand please help someone.

1

1 Answer 1

1

cellForRowAt is absolutely the wrong place to convert the data.

Simple solution with the Encodable protocol

  • Delete

    var mainLocalArray = [Any]()
    
    
    let arrayLocal = ["\(id)", "\(pro_ID)", housnumber!] as [Any]
    print(arrayLocal)
    self.mainLocalArray.append(arrayLocal)
    print(mainLocalArray)
    

  • In your struct (the type of propertyLocalData) add Encodable and CodingKeys

    struct MyStruct : Encodable {
    
    ...
    
        private enum CodingKeys : String, CodingKey { case id = "properties_id", house_number }
    
    ... }
    
  • In a method (not in cellForRow) encode the data source array

    do {
       let jsonData = try JSONEncoder().encode(propertyLocalData)
       let jsonString = String(data: jsonData, encoding: .utf8)!
       print(jsonString)
    } catch { print(error) }
    

PS: Drop SwiftyJSON.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.