我正在尝试解析json文件以导入我的应用程序的Core Data内部。我正在使用Rubymotion,但没关系,错误与stringWithContentsOfFile
有关。
或者更好的是,错误发生在我的Json文件中。
我从rails后端导出文件,然后用我的应用程序加载它......
seed_file = NSBundle.mainBundle.pathForResource('converted', ofType:'json')
json_string = String.new(NSString.stringWithContentsOfFile(seed_file))
当我尝试加载我的json时,我收到此错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString appendString:]: nil argument'
***
我认为是一些特殊的char,也许是编码。我尝试削减一些json并加载
json_string = String.new(NSString.stringWithContentsOfFile(seed_file, encoding: NSUTF8StringEncoding))
=> "[\n {\n \"id\": 5306,\n \"quiz_type\": \"oltre\",\n \"text\": \"Su quale pubblicazione dell\\'Istituto Idrografico della Marina si possono ricavare informazioni pi√π specifiche sulle maree?\",\n \"flagged\": false,\n \"image\": {\n \"image\": {\n \"url\": \"\"\n }\n },\n \"section\": {\n \"id\": 6,\n \"name\": \"Navigazione\"\n },\n \"answers\": [\n {\n \"id\": 5185,\n \"text\": \"Sul Portolano\",\n \"correct\": false\n },\n {\n \"id\": 5186,\n \"text\": \"Sulle Effemeridi Nautiche\",\n \"correct\": false\n },\n {\n \"id\": 5187,\n \"text\": \"Sulle Tavole di marea\",\n \"correct\": true\n }\n ]\n },\n {\n \"id\": 5305,\n \"quiz_type\": \"oltre\",\n \"text\": \"Cosa indica Zo?\",\n \"flagged\": false,\n \"image\": {\n \"image\": {\n \"url\": \"\"\n }\n },\n \"section\": {\n \"id\": 6,\n \"name\": \"Navigazione\"\n },\n \"answers\": [\n {\n \"id\": 5182,\n \"text\": \"La differenza tra alta e bassa marea sizigiale\",\n \"correct\": false\n }
但是当我尝试解析字符串时,我收到了json中某些字符的错误:例如我有pi√π而不是più
错误在哪里?
答案 0 :(得分:0)
首先,您需要从文件中获取数据。然后你可以得到一个字符串,或者直接去反序列化的JSON对象。
// get file handle
let seedFile = NSBundle.mainBundle().pathForResource("q", ofType:"json")
// get raw data
let data = NSData(contentsOfFile: seedFile!)
// get string from data...
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)
// ...or get array of objects from data
let array = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as [AnyObject]