JSON

Boomerang·2021년 8월 16일
0

Network

목록 보기
2/2

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을 모델로 만들기

json을 decode하는 코드

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)
    }
}

Decodable한 Weather DataType

struct WeatherData: Decodable{
	let name: String
	let main: Main
  	let weather: [Weather]
}

struct Main: Decodable{
	let temp: Double
}

struct Weather: Decodable{
	let description: String
}

decoding struct(Object)만들때 조심해야하는 것

json형식의 이름을 따라야 한다. 예를들어, json에서 temp라는 이름이 들어간 것을 decode하려면 똑같이 temp로 프로퍼티를 이름을 지어야 한다.
json이 temp로 되어있다면,

struct WeatherData: Decodable { 
let temp: Double// ok
let temparature : Double // X
}

decode parameter에 struct이름.self가 들어간 이유

decoder.decode에서는 decoable한 input을 원한다. object가 아니라, decoder.decode(WeatherData, ...)라고 그대로 쓰는게 아니라, decoder.decode(WeatherData.self, ...)로 써줘야 한다
참고로 WeatherData는 위에나오는 struct이다. parameter Data가 아님

let decodedData = ... 를 한 이유는

decode라는 함수가 object을 return한다. 어떤 object이냐면, decoder.decode의 output이 Decodable한 WeatherData Type을 decode한거를 return한다. constant형식으로. 그래서 print(decodedData.name) 이렇게 부를 수 있음

do, try, catch하는이유

오류 막기 위해. 예외처리하는거임

굳이 Main struct나눠서 만든 이유 : json은 tree형식이니까.

json은 tree형식이다. 그래서
...main.temp형식으로 부를 것인데 main을 따로 만들어줘서 tree형식으로 불러준다.

let weather: [Weather] 이건 어떤 type인가?

json형식중에 array로 가져오는 것이 있다. 그래서 property type을 array형식으로 표현하는 방법이다.

profile
Hello World

0개의 댓글