美文网首页
json解析笔记

json解析笔记

作者: Sweet丶 | 来源:发表于2021-09-08 17:59 被阅读0次

    Json解析这里主要是想说明一下options的作用

    1.对象转成jsonString : 进行转化前为了安全最好先判断isValidJSONObject, 原因如下:
    /// Generate JSON data from a Foundation object
    let jsonObj1 = "这是数据" // 1.解析非集合对象options须有.fragmentsAllowed,否则奔溃
    let jsonObj2 = [6] // 数组类型options不需要.fragmentsAllowed也能解析
    let jsonObj3 = ["key":"value"] // 这种是正常的字典
    let jsonObj4 = ["msg" : "haha!", 
                    "data":["key":"value"],
                "fdasfds" :[12]] as [String : Any] // 不需要.fragmentsAllowed能解析
    let jsonObj5 : Set = ["value1", "value2"] // 集合类型加什么options都会奔溃
    
    let bool1 = JSONSerialization.isValidJSONObject(jsonObj1) // false
    let bool2 = JSONSerialization.isValidJSONObject(jsonObj2) // true
    let bool3 = JSONSerialization.isValidJSONObject(jsonObj3)// true
    let bool4 = JSONSerialization.isValidJSONObject(jsonObj4)// true
    let bool5 = JSONSerialization.isValidJSONObject(jsonObj5)// false
    
    let data = try? JSONSerialization.data(withJSONObject: jsonObj, 
    options: [.prettyPrinted, // 1.打印美化,转成字符串会自动加换行符和缩进
    .sortedKeys, // 2.排序key
    .fragmentsAllowed, // 3.允许非字典、非数组类型解析
    .withoutEscapingSlashes])// 4.内容里面包含斜杆"\"时不用添加斜杆转义 
    

    结论:

    func getJSONStringFromDictionary(_ dictionary: Dictionary<AnyHashable, Any>) -> String {
        guard dictionary.count > 0, JSONSerialization.isValidJSONObject(dictionary) else {
            print("非有效json")
            return ""
        }
    // options:参数根据上述的介绍自己选择
        let data = try! JSONSerialization.data(withJSONObject: dictionary, options: [])
        let JSONString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
        return JSONString! as String
    }
    
    2. jsonString转成字典或者数组
    let jsonString1 = "\"aaaa\"" // 要解析非键值对,需要option有.allowFragments
    let jsonString2 = "[{\"key1\":\"value1\", \"key2\" : \"value2\"}, {\"key3\":\"value3\", \"key3\" : \"value3\"}]"// 能解析
    let jsonString3 = "{\"key1\":\"value1\", \"key2\" : \"value2\"}"// 能解析
    let jsonString4 = "{\"data\": [{\"key1\":\"value1\"}, {\"key2\" : \"value2\"}]}"// 能解析
    let jsonString5 = "aaaaaa"// 非键值对或者非""里面的字符串,解析都是空的
    let jsonString = jsonString1
    let jsonObj = getJsonObj(with: jsonString)
    
    func getJsonObj(with jsonString: String) -> Any! {
        guard jsonString.count > 0 else {
            return nil
        }
        let data = jsonString.data(using: String.Encoding.utf8)!
        do {// 在jsonString1时,第一个有.allowFragments能解析,第二个会抛出异常
            let _ = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            let _ = try JSONSerialization.jsonObject(with: data, options: [])
        } catch let error as NSError {
            print(error)
        }
        let jsonObj2 = try? JSONSerialization.jsonObject(with: data, options: [.mutableContainers, // 解析出来数组和字典是可变的
    .mutableLeaves, // 解析出来的字符串是可变的
    .allowFragments])// 允许不是键值对的单独值
        let jsonObj = try? JSONSerialization.jsonObject(with: data, options: [])
        return jsonObj
    }
    

    结论:

    func getJsonObj(with jsonString: String) -> Any! {
        guard jsonString.count > 0 else {
            return nil
        }
        let data = jsonString.data(using: String.Encoding.utf8)!
        let jsonObj = try? JSONSerialization.jsonObject(with: data, options: [])
        return jsonObj
    }
    

    相关文章

      网友评论

          本文标题:json解析笔记

          本文链接:https://www.haomeiwen.com/subject/bsmcwltx.html