本文介绍了使用swift 3从文件加载json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用此代码从文件中加载json字符串.

I am trying to load a json string from a file with this code.

if let filepath = Bundle.main.path(forResource: "data", ofType: "json") {
    do {
        let contents = try String(contentsOfFile: filepath)
        print(contents)
    } catch {
        // contents could not be loaded
        print("could not be loaded")
    }

} else {

}

但是我收到无法加载"消息.代码是否错误?还是应该将文件放在特定的文件夹中?目前,我将其放置在一个名为"models"的文件夹中.

But I get the "could not be loaded" message. Is the code wrong? or shall I put the file in a specific folder? At the moment I am putting it a a folder called models.

编辑:我检查了错误内容,并且json文件的位置没有问题,当我尝试将其转换为String时出现问题.它告诉我编码是不同的...

I checked the error content and there is no problem with the location of the json file, the problemoccure when I try to convert it to a String. It tells me that the encoding is different ...

推荐答案

首先请确保已标记copy item if needed复选标记,并且在添加.json文件的同时也标记了目标,之后的主要问题是您加载文件的方式,需要使用Data而不是String

First make sure that you have marked the copy item if needed checkmark, and your target is marked also while you add your .json file, after that your main issue is your way to load your file, you need to do this with Data instead of String

使用此方法加载json并在回调中获取结果

     func loadJSON(finishedClosure:@escaping ((_ jsonObject:[String:AnyObject]?,_ error: NSError?) ->Void))
{
    DispatchQueue.global().async {
        guard let path = Bundle.main.path(forResource: "yourJSON", ofType: "json") else{
            DispatchQueue.main.async {
                finishedClosure(nil, NSError(domain: "JSON file don't founded", code: 998, userInfo: nil))
            }
            return
        }
        //Load file data part
        guard let jsonData = (try? Data(contentsOf: URL(fileURLWithPath: path))) else{
            DispatchQueue.main.async {
                finishedClosure(nil, NSError(domain: "can convert to data", code: 999, userInfo: nil))
            }
            return
        }

        do {
            if let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String:AnyObject]
            {
                DispatchQueue.main.async {
                    finishedClosure(jsonObject,nil)
                }
            }
        } catch let error as NSError {
            print(error)
            DispatchQueue.main.async {
                finishedClosure(nil,error)
            }
        }
    }
}

这篇关于使用swift 3从文件加载json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 06:06