iOS Swift read local json file error reporting solution

  • 2020-05-30 21:10:22
  • OfStack

preface

Recently, I have been idling for a long time. I have read a local json file, but I did not expect to find the following error when loading the local json file 1 with the Swift test data:


Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

It was originally a local json file with a comment in front of it /* chrome-extension://pkgccpejnmalmdinmhkkfafefagiiiad/template/fehelper_jsonformat.html */ Then you can't read to the ' ' 'pit, remove the comments can read normally


let path = Bundle.main.path(forResource: "countryData", ofType: "json")
let url = URL(fileURLWithPath: path!)
//  with throws The method to throw an exception 
 do {
    /*
     * try  and  try!  The difference between 
     * try  When an exception occurs, it jumps catch In the code 
     * try!  An exception occurs directly to the program crash
     */
   let data = try Data(contentsOf: url)
   let jsonData:Any = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers)
   let jsonArr = jsonData as! NSArray
   
   for dict in jsonArr {
    print(dict)
   }
  } catch let error as Error! {
   print(" An error occurred reading local data !",error)
  }

Read more -- Error Handling

conclusion


Related articles: