作者:mobiledu2502861407 | 来源:互联网 | 2023-08-25 19:38
Swift之JSONEncoder和JSONDecoder摘自官方文档:Atypethatcanconvertitselfintoandoutofanextern
Swift 之 JSONEncoder 和 JSONDecoder 摘自官方文档:
public typealias Codable = Decodable & Encodable
对象进行jsonEncode和jsonDecode 一个对象如果需要被编码/解码的话,该对象所属的类需要遵循 Decodable
& Encodable
协议。
以 Player 这类为例,Player遵循了 Decodable 和 Encodable
import Foundation struct Player : Codable { var name: String var highScore: Int &#61; 0 var history: [ Int ] &#61; [ ] enum CodingKeys : String , CodingKey { case name &#61; "Name" case highScore &#61; "HighScore" case history &#61; "History" } init ( _ name: String ) { self . name &#61; name} } extension Player { mutating func updateScore ( _ newScore: Int ) { history. append ( newScore) if highScore < newScore { print ( "\( newScore) ! A new high score for \( name) ! &#x1f389;" ) highScore &#61; newScore} } }
初始化一个Player对象&#xff0c;并对其进行编码和解码&#xff0c;看看编码和解码之后的数据
var jsonData: Data ? var player &#61; Player ( "Tomas" ) player. updateScore ( 50 ) let encoder &#61; JSONEncoder ( ) do { let data: Data &#61; try encoder. encode ( player) print ( data) print ( String ( data: data, encoding: String . Encoding . utf8) as Any ) print ( player) jsonData &#61; data} catch { } let decoder &#61; JSONDecoder ( ) do { let player: Player &#61; try decoder. decode ( Player . self , from: jsonData! ) print ( player) print ( player. name) } catch { }
一个对象被jsonEncode后&#xff0c;对象将被转成 Data 类型的数据。 再将对象的 Data 数据通过jsonDecode&#xff0c;可以还原原来的对象。
通过对对象的json编码和解码&#xff0c;有助于我们理解数据在计算机中的存储。Data 其本质就是二进制流。
JSON字符串转模型 这是一个字符串
let jsonString: String &#61; "" "{ "name" : "Tomas" , "highScore" : 50 , "history" : [ 30 , 40 , 50 ] } "" "
如何将其解析成player对象&#xff1f;
let jsonData: Data &#61; jsonString. data ( using: String . Encoding . utf8) ! let decoder &#61; JSONDecoder ( ) do { let player: Player &#61; try decoder. decode ( Player . self , from: jsonData) print ( player) print ( player. name) } catch { }
这种情况多用于客户端向服务端发送HTTP请求之后&#xff0c;解析返回数据&#xff0c;如果后台返回的是标准的JSON字符串的话直接这样解析就可以了。
JSONSerialization Serialization 是序列化的意思&#xff0c;JSONSerialization 顾名思义是对JSON进行序列化。
JSONSerialization 是对 JSON 字符串进行序列化和反序列化的工具类。用这个类可以将JSON转成对象&#xff0c;也可以将对象转成JSON。
let dict: [ String : Any ] &#61; [ "name" : "Tomas" , "highScore" : 50 , "history" : [ 30 , 40 , 50 ] ] if JSONSerialization . isValidJSONObject ( dict) &#61;&#61; false { return } let data: Data &#61; try ! JSONSerialization . data ( withJSONObject: dict, options: . fragmentsAllowed) let string &#61; String ( data: data, encoding: String . Encoding . utf8) print ( string as Any )
打印结果&#xff1a;
Optional ( "{\"history\":[30,40,50],\"name\":\"Tomas\",\"highScore\":50}" )
这是一个标准的&#xff0c;带转义的JSON字符串。也就是说我们将字典转成了JSON字符串。
let jsonString &#61; "{\"history\":[30,40,50],\"name\":\"Tomas\",\"highScore\":50}" let data &#61; jsonString. data ( using: String . Encoding . utf8) let dict &#61; try ! JSONSerialization . jsonObject ( with: data! , options: . allowFragments) print ( dict)
打印结果&#xff1a;
{ highScore &#61; 50 ; history &#61; ( 30 , 40 , 50 ) ; name &#61; Tomas ; }
参考 [1] JSONEncoder文档&#xff1a;https://developer.apple.com/documentation/foundation/jsonencoder/ [2] JSONDecoder文档&#xff1a;https://developer.apple.com/documentation/foundation/jsondecoder [3] JSONSerialization文档&#xff1a;https://developer.apple.com/documentation/foundation/jsonserialization