簡體   English   中英

如何在 swift 4 中解析 Json 字典

[英]How to Parse Json dictonary in swift 4

嗨,我對這個 Json 有問題:

{
    "id": "libMovies",
    "jsonrpc": "2.0",
    "result": {
        "limits": {
            "end": 75,
            "start": 0,
            "total": 1228
        },
        "movies": [{
            "art": {
                "fanart": "myfanart",
                "poster": "myposter"
            },
            "file": "myfile",
            "label": "mylable",
            "movieid": mymovieid,
            "playcount": 0,
            "rating": myrating,
            "thumbnail": "mythumbnail"
        }]
    }
}

當我使用此代碼在 swift 5 中解析 Json 時

try! JSONDecoder().decode([MyMovie].self, from: data!)

我收到這個錯誤

致命錯誤:“嘗試!” 表達式意外引發錯誤:Swift.DecodingError.typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary 相反。",underlyingError: nil)):

我該如何解決這個問題?

對於下面的 JSON,

{"id":"libMovies","jsonrpc":"2.0","result":{"limits":{"end":75,"start":0,"total":1228},"movies":[{"art":{"fanart":"myfanart","poster":"myposter"},"file":"myfile","label":"mylable","movieid":"mymovieid","playcount":0,"rating":"myrating","thumbnail":"mythumbnail"}]}}

您需要使用的Codable模型,

struct Root: Decodable {
    let id, jsonrpc: String
    let result: Result
}
struct Result: Decodable {
    let limits: Limits
    let movies: [Movie]
}

struct Limits: Decodable {
    let end, start, total: Int
}

struct Movie: Decodable {
    let art: Art
    let file, label, movieid: String
    let playcount: Int
    let rating, thumbnail: String
}
struct Art: Decodable {
    let fanart, poster: String
}

像這樣解析JSON data

do {
    let response = try JSONDecoder().decode(Root.self, from: data)
    print(response.result.movies.map({"file: \($0.file), label: \($0.label)"}))
} catch {
    print(error)
}

編輯:

要單獨保存電影,請創建一個類型為 [Movie] 的變量,

var movies = [Movie]()

現在,在解析時將response.result.movies保存在上面創建的屬性中,

do {
    let response = try JSONDecoder().decode(Root.self, from: data)
    print(response.result.movies.map({"file: \($0.file), label: \($0.label)"}))
    movies = response.result.movies
} catch {
    print(error)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM