GURU
GURU

Reputation: 323

read/write local json file swift 4

Please help me! I added a json file to the project My json file:

{
  "person": [
    {
      "title": "Витамин А",
      "image": "Vitamin1",
      "favorite": false
    },
    {
      "title": "Витамин B6",
      "image": "Vitamin2",
      "favorite": false
    }
  ]
}

I can read file:

struct ResponseData: Decodable {
    var person: [Person]
}

struct Person : Decodable {
    var title: String
    var image: String
    var favorite: Bool
}

Load json from file fonction:

func loadJson(filename fileName: String) -> [Person]? {
    if let url = Bundle.main.url(forResource: fileName, withExtension: "json") {
        do {
            let data = try Data(contentsOf: url)
            let decoder = JSONDecoder()
            let jsonData = try decoder.decode(ResponseData.self, from: data)
            return jsonData.person
        } catch {
            print("error:\(error)")
        }
    }
    return nil
}

var VTarray2 = [Person]()

override func viewDidLoad() {
    super.viewDidLoad()

    VTarray2 = loadJson(filename: "document")!
    VTarray2[0].favorite = true
}

I write function and I get my edit json! Now I need to write json in the file

func encoderJsonFiles() { 
    let encoder = JSONEncoder()
    do {
        let jsonData = try encoder.encode(VTarray2)
        if let jsonString = String(data: jsonData, encoding: .utf8) {
           print(jsonString)
        }
    } catch {
            print(error.localizedDescription)
    }
 }

I write function for save to file

func SaveToFile(){
 let file = "Myfile.json" 

            if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {

                let fileURL = dir.appendingPathComponent(file)

                do {
                    let jsonData = try encoder.encode(VTarray2)
                    try jsonData.write(to: fileURL)
                }
                catch {/* error handling here */}
}

Add function LoadFromJsonFile() I read data. but I can't decode them in JSON format How do I parse data?

func LoadFromJsonFile() {
    let fileURL = UserDefaults.standard.url(forKey: "fileURL")!
    do {
        let myJSON = try String(contentsOf: fileURL, encoding: .utf8)
        print("JSONLoad : \(myJSON)")
        print("JSONPath: \(fileURL)")
    }
    catch {print("Error")}
}

Thank you!

Upvotes: 5

Views: 7899

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100541

Use

struct ResponseData: Codable {

to be able to decode

let dic = try decoder.decode(ResponseData.self, from: data)

and encode

let data = try JSONEncoder().encode(item)

Upvotes: 5

Related Questions