Swift: Convert struct to JSON?

后端 未结 3 1699
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-03 17:20

I created a struct and want to save it as a JSON-file.

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

var s = Sentence()
s.sen         


        
3条回答
  •  一生所求
    2020-12-03 17:37

    Swift 4 supports the Encodable protocol e.g.

    struct Sentence: Encodable {
        var sentence: String?
        var lang: String?
    }
    
    let sentence = Sentence(sentence: "Hello world", lang: "en")
    

    Now you can automatically convert your Struct into JSON using a JSONEncoder:

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

    Print it out:

    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

提交回复
热议问题