Swift 3 및 Swift 4 String에는이라는 메소드가 data(using:allowLossyConversion:)있습니다. data(using:allowLossyConversion:)다음과 같은 선언이 있습니다.
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
주어진 인코딩을 사용하여 인코딩 된 문자열 표현이 포함 된 데이터를 반환합니다.
스위프트 4, String'들 data(using:allowLossyConversion:)과 함께 이용 될 수 JSONDecoder의 decode(_:from:)사전에 JSON 문자열을 직렬화하기 위해.
또한, 신속한 3 스위프트 4, String'들 data(using:allowLossyConversion:)도 함께 함께 이용 될 수 JSONSerialization의 jsonObject(with:options:)사전에 JSON 문자열을 직렬화하기 위해.
#1. 스위프트 4 솔루션
Swift 4 JSONDecoder에는이라는 메소드가 decode(_:from:)있습니다. decode(_:from:)다음과 같은 선언이 있습니다.
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
주어진 JSON 표현에서 주어진 유형의 최상위 값을 디코딩합니다.
사용하는 방법을 보여줍니다 아래의 놀이터 코드 data(using:allowLossyConversion:)및 decode(_:from:)순서는 얻을 수 DictionaryJSON에서 포맷 String:
let jsonString = """
{"password" : "1234", "user" : "andreas"}
"""
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let decoder = JSONDecoder()
let jsonDictionary = try decoder.decode(Dictionary<String, String>.self, from: data)
print(jsonDictionary) // prints: ["user": "andreas", "password": "1234"]
} catch {
// Handle error
print(error)
}
}
# 2. 스위프트 3 및 스위프트 4 솔루션
Swift 3 및 Swift 4 JSONSerialization에는이라는 메소드가 jsonObject(with:options:)있습니다. jsonObject(with:options:)다음과 같은 선언이 있습니다.
class func jsonObject(with data: Data, options opt: JSONSerialization.ReadingOptions = []) throws -> Any
주어진 JSON 데이터에서 Foundation 객체를 반환합니다.
사용하는 방법을 보여줍니다 아래의 놀이터 코드 data(using:allowLossyConversion:)및 jsonObject(with:options:)순서는 얻을 수 DictionaryJSON에서 포맷 String:
import Foundation
let jsonString = "{\"password\" : \"1234\", \"user\" : \"andreas\"}"
if let data = jsonString.data(using: String.Encoding.utf8) {
do {
let jsonDictionary = try JSONSerialization.jsonObject(with: data, options: []) as? [String : String]
print(String(describing: jsonDictionary)) // prints: Optional(["user": "andreas", "password": "1234"])
} catch {
// Handle error
print(error)
}
}