JSON


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のコード

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
}

復号構造(Object)を作成するときは注意してください


jsonフォーマットに従う名前.たとえば、jsonにtempの名前が含まれている場合は、同じようにtempを使用してpropertyと名前を付ける必要があります.
jsonがtempなら、
struct WeatherData: Decodable { 
let temp: Double// ok
let temparature : Double // X
}

decodeパラメータの構造名。selfが入った理由


decoder.decodeには復号可能な入力が必要です.objectではなくデコーダdecode(WeatherData, ...)そう書くのではなくデコーダdecode(WeatherData.self, ...)として
参考までにWeatherDataは上の構造です.非パラメータデータ

let decodedData = ... どうして


decodeという関数は、オブジェクトを返します.どんなオブジェクトなのかデコーダdecodeの出力は、Decodable WeatherDataタイプのdecodeを返します.定数形式でだからprint(decodeData.name)と呼ぶことができます

do、try、catchの原因


間違いを防ぐために例外処理

なぜMain structに分けて作らなければならないのか:jsonは木の形だからです。


jsonは木の形です.だから.
...main.私はtempの形式で歌いますが、mainを別途作成して木の形式で歌います.

let weather:[Weather]これはどんなタイプですか。


jsonフォーマットにインポート配列があります.したがって,property typeをarrayフォーマットとして表す方法である.