투케이2K

69. (ios/swift) json 데이터 딕셔너리로 파싱 및 boolean to string 데이터 형변환 본문

IOS

69. (ios/swift) json 데이터 딕셔너리로 파싱 및 boolean to string 데이터 형변환

투케이2K 2021. 12. 3. 14:33

[개발 환경 설정]

개발 툴 : XCODE

개발 언어 : SWIFT

 

[소스 코드]

            // 로직 [1] : [서버 통신으로 서버 >> 앱 json response 데이터 받음]



            // 로직 [2] : [딕셔너리 객체 생성 실시 및 json 데이터 받음]
            var jsonObj : Dictionary<String, Any> = [String : Any]()
            do {
                // 딕셔너리에 데이터 저장 실시
                jsonObj = try JSONSerialization.jsonObject(with: Data(receiveData.utf8), options: []) as! [String:Any]
            } catch {
                print("")
                print("===============================")
                print("catch :: ", error.localizedDescription)
                print("===============================")
                print("")
            }
            


            // [정상적으로 json 데이터를 받은 경우]
            if(jsonObj.count > 0){
                
                if jsonObj.keys.contains("name") == true { // 키값이 존재할 경우
                    // [Json String 데이터 확인 및 저장 실시]
                    S_Preference().setString(_sKey: "name", _sValue: jsonObj["name"] as! String) // 프리퍼런스 데이터 저장
                }
                // [비번은 앱 보안 키패드 수행 후 자체적으로 저장 실시]
                if jsonObj.keys.contains("addr") == true { // 키값이 존재할 경우
                    // [Json String 데이터 확인 및 저장 실시]
                    S_Preference().setString(_sKey: "addr", _sValue: jsonObj["addr"] as! String) // 프리퍼런스 데이터 저장
                }
                if jsonObj.keys.contains("sex") == true { // 키값이 존재할 경우
                    // [Json Boolean 데이터 확인 및 String 으로 저장 실시]
                    let auto:Bool = jsonObj["sex"] as! Bool
                    S_Preference().setString(_sKey: "sex", _sValue: sex.description) // 프리퍼런스 데이터 저장
                }
            }

 

반응형
Comments