Swift中的json操作
所属分类:ios | 发布于 2023-01-17 17:32:40
在app开发中,app一般都会和后端进行交互,后端接口返回的是json格式的字符串,对json的操作是必须掌握的技能。
在Swfit中对json操作最常用的是两种方式,使用JSONSerialization或者使用JSONDecoder和JSONEncoder。下面详细介绍这两种方式的使用方法。
1、JSONSerialization
使用JSONSerialization可以方便的对json数据进行编码或者解码。
1.1、使用JSONSerialization对json数据进行解码
swift提供 两个方法对json数据进行解码
/// Returns a Foundation object from given JSON data.
/// 把JSON数据转换成对象,返回Any类型
class func jsonObject(with: Data, options: JSONSerialization.ReadingOptions) -> Any
/// Returns a Foundation object from JSON data in a given stream.
/// 把InputStream流中的数据转换成对象,返回Any类型
class func jsonObject(with: InputStream, options: JSONSerialization.ReadingOptions) -> Any
1.2、使用JSONSerialization对符合格式要求的数据进行JSON编码
swift也提供了两个方法对用于JSON编码
/// Returns JSON data from a Foundation object.
/// 把对象转换成Data类型的数据
class func data(withJSONObject: Any, options: JSONSerialization.WritingOptions) -> Data
/// Writes a given JSON object to a stream.
/// 把JSON对象写入stream流
class func writeJSONObject(Any, to: OutputStream, options: JSONSerialization.WritingOptions, error: NSErrorPointer) -> Int
2、JSONDecoder&&JSONEncoder
2.1、JSONDecoder解码
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
let json = """
{
"name": "Durian",
"points": 600,
"description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
let decoder = JSONDecoder()
let product = try decoder.decode(GroceryProduct.self, from: json)
print(product.name) // Prints "Durian"
2.2、JSONEncoder
struct GroceryProduct: Codable {
var name: String
var points: Int
var description: String?
}
let pear = GroceryProduct(name: "Pear", points: 250, description: "A ripe pear.")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
let data = try encoder.encode(pear)
print(String(data: data, encoding: .utf8)!)
/* Prints:
{
"name" : "Pear",
"points" : 250,
"description" : "A ripe pear."
}
*/