Jason : Javascript Object Notation(표기법)
object형식이 아니라 string형식으로 중요한 내용 담아서 정보전달 좀더 쉽게 할 수 있게 만듬
이케아에서 나사풀고, 물건 쌓아둔 것 처럼 해둔게 json이라면
json형식
"{doors: 2,drawers: 2,colour:"red"}"
집와서 이케아 가구들 조립해서 만든것을 swift object로 만든다
swift형식
var wardrobe = Wardrobe(
doors: 2,
drawers: 2,
colour: "red"
)
Codable = encodable + decodable
Encodable - 모델을 json으로만들기
Decodable - json을 모델로 만들기
func parseJSON(weatherData: Data) {
let decoder = JSONDecoder() // Decode하는 object. initailize했음
do{
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
// type: Decodable.Protocol, from: Data)
print(decodedData.main.temp)
print(decodedData.weather[0].description)
} catch{
print(error)
}
}
struct WeatherData: Decodable{
let name: String
let main: Main
let weather: [Weather]
}
struct Main: Decodable{
let temp: Double
}
struct Weather: Decodable{
let description: String
}
json형식의 이름을 따라야 한다. 예를들어, json에서 temp라는 이름이 들어간 것을 decode하려면 똑같이 temp로 프로퍼티를 이름을 지어야 한다.
json이 temp로 되어있다면,
struct WeatherData: Decodable {
let temp: Double// ok
let temparature : Double // X
}
decoder.decode에서는 decoable한 input을 원한다. object가 아니라, decoder.decode(WeatherData, ...)라고 그대로 쓰는게 아니라, decoder.decode(WeatherData.self, ...)로 써줘야 한다
참고로 WeatherData는 위에나오는 struct이다. parameter Data가 아님
decode라는 함수가 object을 return한다. 어떤 object이냐면, decoder.decode의 output이 Decodable한 WeatherData Type을 decode한거를 return한다. constant형식으로. 그래서 print(decodedData.name) 이렇게 부를 수 있음
오류 막기 위해. 예외처리하는거임
json은 tree형식이다. 그래서
...main.temp형식으로 부를 것인데 main을 따로 만들어줘서 tree형식으로 불러준다.
json형식중에 array로 가져오는 것이 있다. 그래서 property type을 array형식으로 표현하는 방법이다.