1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

JSONデコードして保存とは

Last updated at Posted at 2021-04-14

■JSONデコードして保存とは

データを認識できるように変換して保存する事

実際のJSONデータはこちら

 { //2段階保存 配列
   “weather”:[
            “id”:804
             “main”:”Clouds”
             ]
 //2段階保存
    “main”:{
             “temp”:282.29
             }
 //1段階
    “name”: “London”
 }

■上のJSONデータをデコードしてstructに保存

メソッドにして引数Data型を持し外部からDataをひっぱてくる。

■なんとか.swift の中

func paseraJSON(weatherData: Data)
let json = JSONDecode()

do { let decoder = try json.decode(保存場所.self, flom: weatherData)
       
    }catch {
  print(error)
   }

■structでの保存のしかた (保存する新規ファイルを作成したとする)

■Codableプロトコルを使用 データをデコードしてstructに保存できる用になる。
■Data.swiftの中 デコードしてあるデータなので実際にはここのデータを直接は表示しない

struct Data: Codable {
   
//1段階やからこのまま
   let name:String

//2段階の保存先Struct名を書く    
  let main: Main 

//2段階保存の配列やから新規struct名を[]で囲む
  let weather: [Weather]
}

//2段階保存やから新たにstruct作るイメージはmainの中のtemp
struct Main: Codable {
  let temp: Double
}

//2段階保存かつ配列 まあ上とここは変わらない
struct Weather: Codable {
     let id: Int
}

■strct Dataにデコードして保存した値を実際に使いやすいように

 ■また新規ファイル(WeatherModel)作ってそこに保存し直す

 WeatherModelの中 実際に使う名前や温度などのデータを保存

struct WeatherModel {

   let  cityName: String
   let  conditionID: Int
   let   temperatrue: Double

   var conditionName:String {
   //取得したIDの数字によってコンデイションを文字列型にして分けて取得 後でこの文字と同じ画像を使う
        switch conditionID {
          
        case 200...232:
            return "cloud.bold"
        case 300...321:
            return "cloud.drizzle"
        case 500...531:
            return "cloud.rain"
        case 600...622:
            return "cloud.snow"
        case 701...781:
            return "cloud.fog"
        case 800:
            return "sun.max"
        case 801...804:
            return "cloud.bold"
        default:
            return "cloud"
        }
    }
}

■func paseraJSON(weatherData: Data)を改造

デコードして保存したnameやtempやidなどを
ここで取り出し変数にいれて
新たなstructに入れ込む
返り値を持して 全てデータを入れ込んだstructを返す

func paseraJSON(weatherData: Data) -> WeatherModel?{

let json = JSONDecode()

do{
         let decodeData =  json.decode(weatherData.self,flom:データ名)
         let name = decodeData.name
         let temp =  decodeData.main.temp
         let id = decodeData.weather[0].id

let weather = WeatherModel(cityName: name , temperatrue: temp, conditionID: id )
return weather

} catch {  

     print(error)
 return nil
}

後はsession.dataTaskメソッドの中のタスク等で データを入れたpaseraJSONメソッドを 使用する。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?