요즘 할때마다 검색하게 되는거같아서

JsonEncoder

JsonDecoder

JSONSerializtion.jsonObject

JSONSerializtion.data

에 대해 사용한 예제를 적어봤다.


struct Person:Codable{
    let id:Int
    let name:String
    let sex:String
}

let person = Person(id: 0, name: "홍길동", sex: "male")

do {
    //struct to jsonData
    let jsonData:Data = try JSONEncoder().encode(person) // data
    print(jsonData)
    print()
    
    //jsonData to string
    let jsonString:String = String.init(data: jsonData, encoding: .utf8) ?? "err"
    print(jsonString)
    print()
    
    //string to jsonData
    let jsonData2:Data? = jsonString.data(using: .utf8)
    print(jsonData2)
    print()
    
    //jsonData to dictionary
    let jsonDic = try JSONSerialization.jsonObject(with: jsonData, options: []) as? Dictionary<String, Any> ?? [:]
    print(jsonDic)
    print()
    let jsonDic2 = try JSONSerialization.jsonObject(with: jsonData2!, options: []) as? Dictionary<String,Any> ?? [:]
    print(jsonDic2)
    print()
    
    //dictionary to jsonData
    let jsonData3:Data = try JSONSerialization.data(withJSONObject: jsonDic, options: .sortedKeys)
    print(jsonData3)
    print()
    
    //jsonData to struct
    let structForm:Person = try JSONDecoder().decode(Person.self, from: jsonData)
    print(structForm)
    
} catch let err{
    print("err:\(err.localizedDescription)")
}

 

struct 를 jsonData로 JSONEncoder

string 을 jsonData로 String.data(using: .utf8)//다른 형식으로 지정하면 어떻게 될지 안해봤다.

dictionary 를 jsonData로 JSONSerialization.data

 

jsonData를 string으로 String(data:,encoding:)

jsonData를 struct로 JSONDecoder

jsonData를 dictionary로 JSONSerialization.jsonObject

 

아 헷갈려....

 

+ Recent posts