Swift, NSJSONSerialization and NSError

后端 未结 5 1275
-上瘾入骨i
-上瘾入骨i 2021-02-12 16:19

The problem is when there is incomplete data NSJSONSerialization.JSONObjectWithData is crashing the application giving unexpectedly found nil while unwrappin

5条回答
  •  醉酒成梦
    2021-02-12 17:02

    Swift 3 NSJSONSerialization sample (read json from file):

    file data.json (example from here: http://json.org/example.html)

    {
    "glossary":{
    "title":"example glossary",
    "GlossDiv":{
        "title":"S",
        "GlossList":{
            "GlossEntry":{
                "ID":"SGML",
                "SortAs":"SGML",
                "GlossTerm":"Standard Generalized Markup Language",
                "Acronym":"SGML",
                "Abbrev":"ISO 8879:1986",
                "GlossDef":{
                    "para":"A meta-markup language, used to create markup languages such as DocBook.",
                    "GlossSeeAlso":[
                                    "GML",
                                    "XML"
                                    ]
                },
                "GlossSee":"markup"
            }
        }
    }
    }
    }
    

    file JSONSerialization.swift

    extension JSONSerialization {
    
    enum Errors: Error {
        case NotDictionary
        case NotJSONFormat
    }
    
    public class func dictionary(data: Data, options opt: JSONSerialization.ReadingOptions) throws -> NSDictionary {
        do {
            let JSON = try JSONSerialization.jsonObject(with: data , options:opt)
            if let JSONDictionary = JSON as? NSDictionary {
                return JSONDictionary
            }
            throw Errors.NotDictionary
        }
        catch {
            throw Errors.NotJSONFormat
        }
    }
    }
    

    Usage

     func readJsonFromFile() {
        if let path = Bundle.main.path(forResource: "data", ofType: "json") {
            if let data = NSData(contentsOfFile: path) as? Data {
    
                do {
                    let dict = try JSONSerialization.dictionary(data: data, options: .allowFragments)
                    print(dict)
                } catch let error {
                    print("\(error)")
                }
    
            }
        }
    }
    

    Result (log screenshot)

提交回复
热议问题