Swift 3とSwift 4では、Stringというメソッドがありdata(using:allowLossyConversion:)ます。data(using:allowLossyConversion:)次の宣言があります:
func data(using encoding: String.Encoding, allowLossyConversion: Bool = default) -> Data?
指定されたエンコーディングを使用してエンコードされた文字列の表現を含むデータを返します。
スイフト4で、String「Sはdata(using:allowLossyConversion:)と組み合わせて使用することができJSONDecoder、S」decode(_:from:)辞書にJSON文字列をデシリアライズするために。
また、スウィフト3及びスイフト4で、String'sはdata(using:allowLossyConversion:)またと共に使用することができるJSONSerializationのjsonObject(with:options:)辞書にJSON文字列をデシリアライズするために。
#1。Swift 4ソリューション
Swift 4では、JSONDecoderというメソッドがありdecode(_:from:)ます。decode(_:from:)次の宣言があります:
func decode<T>(_ type: T.Type, from data: Data) throws -> T where T : Decodable
指定されたJSON表現から指定されたタイプのトップレベルの値をデコードします。
以下のPlaygroundコードは、JSON形式からを使用data(using:allowLossyConversion:)しdecode(_:from:)て取得する方法を示しDictionaryています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。Swift 3およびSwift 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オブジェクトを返します。
以下のPlaygroundコードは、JSON形式からを使用data(using:allowLossyConversion:)しjsonObject(with:options:)て取得する方法を示しDictionaryています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)
}
}