简体   繁体   中英

saving json data in coredata in swift

I am trying to save json data which is present in my app bundle. But instead of saving all data it is saving only one data

   func getDignosysListFromJson() {
       let coreData = CoreDataStack()
             let managedObjectContext = coreData.persistentContainer.viewContext
             let dignose = Dignose(context: managedObjectContext)
       let jsonPath = Bundle.main.path(forResource: "dignosys", ofType: "json")
       let jsonUrl = URL(fileURLWithPath: jsonPath!)
       do {
           let data = try Data(contentsOf: jsonUrl)
           let jsonResult = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
           if let newResult = jsonResult as? Array<Dictionary<String, Any>>{
               for i in newResult{
                   let newName = i["dx description"] as! String
                   print(newName)
                   
                   dignose.name = newName
                   dignose.date = "29 Dec 2020"
                  
                   
               }
               
               coreData.saveContext()
               

           }
       } catch {
           print("")
       }
   }

My json structure is:-

[
{"dx type":"what is foot issue","dx description":"Hereditary motor and sensory neuropathy"},
{"dx type":"what is foot issue","dx description":"Multiple sclerosis"},
{"dx type":"use as secondary when only have issue one side","dx description":"gait instability”}
]

Move the line

let dignose = Dignose(context: managedObjectContext)

into the loop

for i in newResult {
    let dignose = Dignose(context: managedObjectContext)
    let newName = i["dx description"] as! String
    print(newName)
   
    dignose.name = newName
    dignose.date = "29 Dec 2020"
}

to get a new instance in each iteration.


The code contains a few questionable practices. I recommend this

func getDignosysListFromJson() {
   let coreData = CoreDataStack()
   let managedObjectContext = coreData.persistentContainer.viewContext
        
   let jsonUrl = Bundle.main.url(forResource: "dignosys", withExtension: "json")!
   do {
       let data = try Data(contentsOf: jsonUrl)
       if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
           for anItem in jsonResult {
               let dignose = Dignose(context: managedObjectContext)
               let newName = anItem["dx description"] as! String
               print(newName)
               
               dignose.name = newName
               dignose.date = "29 Dec 2020"
           }
           coreData.saveContext()
       }
   } catch {
       print(error)
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM