programing

Swift: 구조를 JSON으로 변환하시겠습니까?

goodjava 2023. 3. 11. 08:58

Swift: 구조를 JSON으로 변환하시겠습니까?

작성했습니다.structJSON 파일로 저장하려고 합니다.

struct Sentence {
    var sentence = ""
    var lang = ""
}

var s = Sentence()
s.sentence = "Hello world"
s.lang = "en"
print(s)

...그 결과,

Sentence(sentence: "Hello world", lang: "en")

하지만 어떻게 하면struct다음과 같은 것에 반대합니다.

{
    "sentence": "Hello world",
    "lang": "en"
}

Swift 4는Codable사용자 지정 구조를 인코딩 및 디코딩하는 매우 편리한 방법을 제공하는 프로토콜입니다.

struct Sentence : Codable {
    let sentence : String
    let lang : String
}

let sentences = [Sentence(sentence: "Hello world", lang: "en"), 
                 Sentence(sentence: "Hallo Welt", lang: "de")]

do {
    let jsonData = try JSONEncoder().encode(sentences)
    let jsonString = String(data: jsonData, encoding: .utf8)!
    print(jsonString) // [{"sentence":"Hello world","lang":"en"},{"sentence":"Hallo Welt","lang":"de"}]
    
    // and decode it back
    let decodedSentences = try JSONDecoder().decode([Sentence].self, from: jsonData)
    print(decodedSentences)
} catch { print(error) }

Swift 4는 다음과 같은 Encodable 프로토콜을 지원합니다.

struct Sentence: Encodable {
    var sentence: String?
    var lang: String?
}

let sentence = Sentence(sentence: "Hello world", lang: "en")

이제 JSONEncoder를 사용하여 Structure를 JSON으로 자동 변환할 수 있습니다.

let jsonEncoder = JSONEncoder()
let jsonData = try jsonEncoder.encode(sentence)

인쇄:

let jsonString = String(data: jsonData, encoding: .utf8)
print(jsonString)

{
    "sentence": "Hello world",
    "lang": "en"
}

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

NSJON Serialization 클래스를 사용합니다.

참조용으로 이것을 사용하면, JSON 시리얼 스트링을 반환하는 함수를 작성할 필요가 있는 경우가 있습니다.이 함수에서는 필수 속성을 가져와서 NSDictionary를 만들고 위에서 설명한 클래스를 사용할 수 있습니다.

다음과 같은 경우:

struct Sentence {
    var sentence = ""
    var lang = ""

    func toJSON() -> String? {
        let props = ["Sentence": self.sentence, "lang": lang]
        do {
            let jsonData = try NSJSONSerialization.dataWithJSONObject(props,
            options: .PrettyPrinted)
            return String(data: jsonData, encoding: NSUTF8StringEncoding)
        } catch let error {
            print("error converting to json: \(error)")
            return nil
        }
    }

}

구조체의 속성은 2개뿐이므로 JSON 문자열을 직접 작성하는 것이 더 쉬울 수 있습니다.

다음은 JSON 인코딩/디코딩을 위한 적절한 확장 및 방법입니다.

extension Encodable {
    
    func toJSONString() -> String {
        let jsonData = try! JSONEncoder().encode(self)
        return String(data: jsonData, encoding: .utf8)!
    }
    
}

func instantiate<T: Decodable>(jsonString: String) -> T? {
    return try? JSONDecoder().decode(T.self, from: jsonString.data(using: .utf8)!)
}

사용 예:

struct Sentence: Codable {
    var sentence = ""
    var lang = ""
}

let sentence = Sentence(sentence: "Hello world", lang: "en")
let jsonStr = sentence.toJSONString()
print(jsonStr)      // prints {"lang":"en","sentence":"Hello world"}

let sentenceFromJSON: Sentence? = instantiate(jsonString: jsonStr)
print(sentenceFromJSON!)    // same as original sentence

언급URL : https://stackoverflow.com/questions/33186051/swift-convert-struct-to-json