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"
}
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
'programing' 카테고리의 다른 글
| JSX에서 공백을 추가할 때의 모범 사례 (0) | 2023.03.16 |
|---|---|
| Word Press:$wp_query를 사용하여 카테고리별로 투고를 필터링하려면 어떻게 해야 합니까? (0) | 2023.03.16 |
| MongoDB에 대한 '데이터 손실' 비판은 어느 정도 유효합니까? (0) | 2023.03.11 |
| jQuery를 사용한 병렬 비동기 Ajax 요청 (0) | 2023.03.11 |
| 몽구스:CastError: 경로 "_id"에서 값 "개체 개체"에 대해 ObjectId로 캐스팅하지 못했습니다. (0) | 2023.03.11 |