2017년 7월 16일 일요일

Swift 4의 JSON 인코더와 디코더 사용 데모입니다.

Xcode 9.0 beta3에서 iOS 11.0에 대한 테스트들입니다.

JSON EncodingDecoding
좀 더 간편하게 JSON포맷을 처리할 수 있게 됨

DemoSwift4로 저장함

아래와 같이 Tutorial클래스 파일을 추가한다.
//
//  Tutorial.swift
//  DemoSwift4
//
//  Created by jong deok Kim on 2017. 7. 17..
//  Copyright © 2017 credu. All rights reserved.
//

import Foundation

class Tutorial: Codable {
    let title: String
    let author: String
    let editor: String
    let type: String
    let publishDate: Date
   
    init(title: String, author: String, editor: String, type: String, publishDate: Date) {
        self.title = title
        self.author = author
        self.editor = editor
        self.type = type
        self.publishDate = publishDate
    }
}


버튼을 3개 추가해서 아래와 같이 코딩한다.
//
//  ViewController.swift
//  DemoSwift4
//
//  Created by jong deok Kim on 2017. 7. 17..
//  Copyright © 2017 credu. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBAction func btn1(_ sender: Any) {
       
        let tutorial = Tutorial(title: "스위프트4 새로운 ", author: "papasmf", editor: "kim", type: "새로운 기능", publishDate: Date())
        //위의 객체를 바로 JSON포맷으로 인코딩해서 리턴한다.
        let encoder = JSONEncoder()
        do {
            let data = try encoder.encode(tutorial)
            let string = String(data: data, encoding: .utf8)
            print(string ?? "")
       
            let decoder = JSONDecoder()
            let article = try decoder.decode(Tutorial.self, from: data)
            let info = "\(article.title) \(article.author) "
                + "\(article.editor) \(article.type) \(article.publishDate)"
            print(info)
        } catch {
       
        }
       
    }
   
    @IBAction func btn2(_ sender: Any) {
    }
   
    @IBAction func btn3(_ sender: Any) {
    }
   
   
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

결과는 아래와 같이 출력된다.
{"author":"papasmf","title":"스위프트4 새로운 ","publishDate":522004473.74601197,"type":"새로운 기능","editor":"kim"}
스위프트4 새로운 papasmf kim 새로운 기능 2017-07-17 17:14:33 +0000







댓글 없음:

댓글 쓰기

참고: 블로그의 회원만 댓글을 작성할 수 있습니다.

요즘 새로운 과정을 기획하면서 react.js + next.js를 OpenAI API와 같이 사용하는 과정을 만들고 있습니다. ㅎㅎ

 오랜만에 웹 기술들을 공부하니 재미있네요. ㅎㅎ  쭉 파이썬 과정들을 운영하고 있었는데 좀 더 범위를 넓혀서 아이폰 앱 개발과정 with ChatGPT,  웹 프로그래밍 with ChatGPT, AI시대의 AI어시스턴트 활용하기와 같은 글을 쓰고, ...