ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • txt 파일 json 파싱하기
    iOS/개념정리 2022. 1. 24. 13:43

    1. Codable

     

    - swift4 부터 추가된 프로토콜로,  Json data를 간편하고 쉽게, Decoding/Encoding 해준다.

    - 실제 코드로는 아래와 같이 정의 되어 있다.

    codable code

    - Encodable/Decodable를 준수하는 프로토콜 이다.

    - Class, Struct, Enum 모두 Codable를 채택할 수 있다.

     

    2. Encoding / Decoding

     

    - Encoding

        struct, enum, class 등의 인스턴스를 Json data 형태로 변환 시켜 주는 것.

    - Decoding

        Json 형태의 data를 struct, enum, class 등의 인스턴스에 파싱.

     

    3. txt 파일 읽어오기

     

        3-1. 파일 데이터 형식으로 가져오기

    if let filepath = Bundle.main.path(forResource: "FILENAME", ofType: "txt") {
                do {
                	//읽어 오기 성공
                    let contents = try String(contentsOfFile: filepath)
                    //data에 텍스트 파일의 텍스트를 저장한다.
                    let data = contents.data(using: .utf8) 
    				
                    }
                } catch {
                    print("Error")
                }
            } else {
                print("Error")
            }

        3-2. model  만들기

     

        - json 형태에 맞춰서 model을 만들어 준다.

        - Codable 사용

    struct Room: Codable{
        var id: Int
        var title: String
        var contents: String
        
        enum Codingkeys: String, CodingKey{
            case id, title, contents
        }
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            
            id = (try? values.decode(Int.self, forKey: .id)) ?? 0
            title = (try? values.decode(String.self, forKey: .title)) ?? ""
            contents = (try? values.decode(String.self, forKey: .contents)) ?? ""
        }
    }
    //Room형태의 리스트
    struct RoomsData: Codable{
        var rooms: [Room]?
    }

     

        3-3. json parsing 하기

     

        - roomList에 파싱

    var roomList : [Room] = []
    if let data = data, let roomsData = try? decoder.decode(RoomsData.self, from: data) {
        guard let nonOptionalRooms = roomsData.rooms else{
            return
    }
    
    roomList = nonOptionalRooms

    'iOS > 개념정리' 카테고리의 다른 글

    <Swift> Delegate  (1) 2022.01.25
    <Swift> Firebase 연동  (0) 2022.01.25
    Alamofire 이용한 Server 통신  (0) 2022.01.24
    Swift MVVM 패턴  (0) 2022.01.21
    프로젝트 생성(storyboard 아닌 xib 사용)  (1) 2022.01.21

    댓글

Designed by Tistory.