JSONDecoder的使用

image.png
  • An object that decodes instances of a data type from JSON objects.

    从JSON对象解码数据类型实例的对象。

Overview

  • The example below shows how to decode an instance of a simple GroceryProduct type from a JSON object. The type adopts Codable so that it's decodable using a JSONDecoderinstance.

    下面的示例显示了如何从JSON对象解码“简单GroceryProduct类型”的实例。 该类型采用Codable,因此可以使用JSONDecoder实例进行解码。

let json = """
{
    "name": "Durian",
    "points": 600,
    "description": "A fruit with a distinctive scent."
}
""".data(using: .utf8)!
struct GroceryProduct: Codable {
    var name: String
    var points: Int
    var description: String?
}
let decoder = JSONDecoder() 
do {
    let product = try decoder.decode(GroceryProduct.self, from: json)
    print(product)
    print(product.name)
    print(product.points)
    print(product.description)
 } catch {
    print(error)
}

Question

image.png
  • type: Decodable.Protocol ,什么是Decodable.protocol,这个位置为什么我们需要填入什么,为什么要填SomeProtocol.self
image.png

元类型是指类型的类型,包括类类型、结构体类型、枚举类型和协议类型。

类、结构体或枚举类型的元类型是相应的类型名紧跟 .Type。协议类型的元类型——并不是运行时符合该协议的具体类型——而是该协议名字紧跟 .Protocol。比如,类 SomeClass 的元类型就是 SomeClass.Type,协议 SomeProtocol 的元类型就是 SomeProtocal.Protocol。

你可以使用后缀 self 表达式来获取类型。比如,SomeClass.self 返回 SomeClass 本身,而不是 SomeClass 的一个实例。同样,SomeProtocol.self 返回 SomeProtocol 本身,而不是运行时符合 SomeProtocol 的某个类型的实例。还可以对类型的实例使用 type(of:) 表达式来获取该实例在运行阶段的类型,如下所示:

下面我们从实际应用来探索

protocol someProtocol {}

func testA(_ type: T.Type, from data: Data)  {
      /// do somethingg
}

class TestClass: someProtocol {}
enum TestEnum: someProtocol {}
struct TestStruct: someProtocol {}
image.png

在方法testA中,第一个参数需要我们传递一个泛型类型T的元类型,泛型类型T 遵守someProtocol 协议,所以不管传递进去的是什么类型(class, 枚举,结构体)的元类型,这个类型本身必须遵守someProtocol 协议。

与没有约束要求的约束相比

func printGenericInfo(_ value: T) {
    let type = type(of: value)
    print("'\(value)' of type '\(type)'")
}

protocol P {}
extension String: P {}

let stringAsP: P = "Hello!"
printGenericInfo(stringAsP)
// 'Hello!' of type 'P'
image.png

Discussion

If the data is not valid JSON, this method throws the DecodingError.dataCorrupted(_:) error. If a value within the JSON fails to decode, this method throws the corresponding error.

如果数据无效JSON,则此方法抛出DecodingError.dataCorrupted(_ :)错误。 如果JSON中的值无法解码,则此方法将引发相应的错误。

DecodingError.dataCorrupted(_:)
An indication that the data is corrupted or otherwise invalid.

指示数据已损坏或无效。

Declaration

case dataCorrupted(DecodingError.Context)

Discussion

As an associated value, this case contains the context for debugging.

作为关联值,此案例包含调试的上下文。

你可能感兴趣的:(JSONDecoder的使用)