요즘 할때마다 검색하게 되는거같아서
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
아 헷갈려....
반응형
'iOS > swift' 카테고리의 다른 글
한글 자모의 유니코드에 대한 글 (0) | 2021.02.03 |
---|---|
class JSONNull (0) | 2021.01.19 |
문자열 내부의 단어를 찾는 방법 (0) | 2020.11.25 |
LAError Code (구글 번역기) (0) | 2020.09.16 |
Firebase를 다루면서 계속해서 가져온 라이브러리문제가 발생한이유 (0) | 2020.08.20 |