JSONDecoder的使用

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

    從JSON對象解碼數(shù)據(jù)類型實例的對象。

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實例進(jìn)行解碼。

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

元類型是指類型的類型,包括類類型、結(jié)構(gòu)體類型、枚舉類型和協(xié)議類型。

類、結(jié)構(gòu)體或枚舉類型的元類型是相應(yīng)的類型名緊跟 .Type。協(xié)議類型的元類型——并不是運(yùn)行時符合該協(xié)議的具體類型——而是該協(xié)議名字緊跟 .Protocol。比如,類 SomeClass 的元類型就是 SomeClass.Type,協(xié)議 SomeProtocol 的元類型就是 SomeProtocal.Protocol。

你可以使用后綴 self 表達(dá)式來獲取類型。比如,SomeClass.self 返回 SomeClass 本身,而不是 SomeClass 的一個實例。同樣,SomeProtocol.self 返回 SomeProtocol 本身,而不是運(yùn)行時符合 SomeProtocol 的某個類型的實例。還可以對類型的實例使用 type(of:) 表達(dá)式來獲取該實例在運(yùn)行階段的類型,如下所示:

下面我們從實際應(yīng)用來探索

protocol someProtocol {}

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

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

在方法testA中,第一個參數(shù)需要我們傳遞一個泛型類型T的元類型,泛型類型T 遵守someProtocol 協(xié)議,所以不管傳遞進(jìn)去的是什么類型(class, 枚舉,結(jié)構(gòu)體)的元類型,這個類型本身必須遵守someProtocol 協(xié)議。

與沒有約束要求的約束相比

func printGenericInfo<T>(_ 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.

如果數(shù)據(jù)無效JSON,則此方法拋出DecodingError.dataCorrupted(_ :)錯誤。 如果JSON中的值無法解碼,則此方法將引發(fā)相應(yīng)的錯誤。

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

指示數(shù)據(jù)已損壞或無效。

Declaration

case dataCorrupted(DecodingError.Context)

Discussion

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

作為關(guān)聯(lián)值,此案例包含調(diào)試的上下文。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容