iOS JSON解析 - Codable



  • Swift版本: 4.0

    通过 Codable 协议实现Swift对象与json字符串之间的互转。

    简单数据结构

    • 定义数据结构 User
    struct User: Codable {
        var name: String
        var age: Int
    }
    
    • json字符串 -> User对象
    let jsonStr = """
    {
        "name": "zzb",
        "age": 18
    }
    """
            
    let jsonData = jsonStr.data(using: .utf8)!
    
    let decoder = JSONDecoder()
    
    do {
        let userObj = try decoder.decode(User.self, from: jsonData)
        print("userObj = \(userObj)")
    } catch {
        print("Decode error")
    }
    
    • User对象 -> json字符串
    let user = User(name: "Cary", age: 20)
            
    let encoder = JSONEncoder()
    do {
        let data = try encoder.encode(user)
        let dataStr = String(data: data, encoding: .utf8)
        print("dataStr = \(String(describing: dataStr))")
    } catch {
        print("Encode error")
    }
    

    复杂数据结构

    • 定义数据结构 AdvancedUser
    enum Gender: Int, Codable {
        case male = 1
        case female
    }
    
    class Location: Codable {
        var lat: Double = 0.0
        var lon: Double = 0.0
    }
    
    struct AdvancedUser: Codable {
        var name: String
        var age: Int
        var gender: Gender
        var location: Location
    }
    
    • json字符串 -> AdvancedUser对象
    let jsonStr = """
    {
        "name": "zzb",
        "age": 18,
        "gender": 2,
        "location": {
            "lat": 99.9,
            "lon": 87.5
        }
    }
    """
    
    let jsonData = jsonStr.data(using: .utf8)!
    
    let decoder = JSONDecoder()
    
    do {
        let userObj = try decoder.decode(AdvancedUser.self, from: jsonData)
        print("userObj = \(userObj)")
    } catch {
        print("Decode error")
    }
    
    • AdvancedUser对象 -> json字符串
    let location = Location()
    location.lat = 99.9
    location.lon = 87.5
    let user = AdvancedUser(name: "Cary", age: 19, gender: .male, location: location)
    
    let encoder = JSONEncoder()
    do {
        let data = try encoder.encode(user)
        let dataStr = String(data: data, encoding: .utf8)
        print("dataStr = \(String(describing: dataStr))")
    } catch {
        print("Encode error")
    }
    

    Demo源码

    https://github.com/CaryZheng/iOSTutorials


Log in to reply