iOS(swift) json转对象,对象转Data,对象转String,对象转dictionary,dictionary转Data,dictionary转String

解决问题

1、将jsonString转为对象
2、将jsonData转为对象
3、将对象编码成JsonData
4、将对象编码成Json字符串
5、将对象编码成Json字典
6、字典转Json字符串
7、字典转JsonData

实现方法

extension Decodable {
    /// 将传入参数转为对象
    /// - Parameter obj: JSONSerialization的对象
    /// - Throws: 数据错误时抛出错误
    /// - Returns: 返回解码后的对象
    public static func decode(from obj: Any) throws -> Self {
        if let jsonStr = obj as? String {
            return try decode(fromString: jsonStr)
        } else if let jsonData = obj as? Data {
            return try decode(fromData: jsonData)
        } else {
            let data = try JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted)
            return try decode(fromData: data)
        }
    }
    
    /// 将jsonData转为对象
    /// - Parameter jsonData: jsonData
    /// - Throws: 数据错误时抛出错误
    /// - Returns: 返回解码后的对象
    private static func decode(fromData jsonData: Data) throws -> Self {
        return try JSONDecoder().decode(Self.self, from: jsonData)
    }
    
    /// 将jsonString转为对象
    /// - Parameter jsonString: json字符串
    /// - Throws: 数据错误时抛出错误
    /// - Returns: 返回解码后的对象
    private static func decode(fromString jsonString: String) throws -> Self {
        guard let data = jsonString.data(using: .utf8) else {
            let error = NSError(domain: "decode failed", code: -1)
            throw error
        }
        return try JSONDecoder().decode(Self.self, from: data)
    }
}

extension Encodable {
    
    /// 将对象编码成JsonData
    /// - Parameter option: 选项
    /// - Throws: 数据错误时抛出编码错误
    /// - Returns: 编码后的Data
    public func toJsonData(option:JSONEncoder.OutputFormatting = []) throws -> Data {
        let encoder = JSONEncoder()
        encoder.outputFormatting = option
        return try encoder.encode(self)
    }
    
    /// 将对象编码成Json字符串
    /// - Parameter option: 选项
    /// - Throws: 数据错误时抛出编码错误
    /// - Returns: 编码后的字符串
    public func toJsonString(option:JSONEncoder.OutputFormatting = []) throws -> String {
        let data = try toJsonData(option: option)
        guard let str = String(data: data, encoding: .utf8) else {
            throw NSError(domain: "toJsonString failed", code: -1)
        }
        return str
    }
    
    /// 将对象编码成Json字典
    /// - Throws: 数据错误时抛出编码错误
    /// - Returns: 数据字典
    public func toJsonDic() throws -> [String: Any] {
        let data = try toJsonData()
        let dic = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
        guard let json = dic as? [String: Any] else {
            throw NSError(domain: "toJsonDic failed", code: -1)
        }
        return json
    }
    
    /// jsonData
    public var jsonData: Data? {
        try? toJsonData()
    }

    /// jsonString
    public var jsonString: String? {
        try? toJsonString()
    }
    
    /// jsonDic
    public var jsonDic: [String: Any]? {
        try? toJsonDic()
    }
}

extension Dictionary {
    /// 转成json字符串
    public func toJson(option:JSONSerialization.WritingOptions = []) throws -> String {
        let data = try toJsonData(option: option)
        guard let str = String(data: data, encoding: .utf8) else {
            throw EncodingError.invalidValue(self, EncodingError.Context(codingPath: [], debugDescription: "Convert to json failed because of invalid data"))
        }
        return str
    }
    
    /// 转成json Data
    public func toJsonData(option:JSONSerialization.WritingOptions = []) throws -> Data {
        let data = try JSONSerialization.data(withJSONObject: self, options: option)
        return data
    }
    
}


  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张子都

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值