如何在 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!)

我收到这个错误

Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", 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: \([=12=].file), label: \([=12=].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: \([=14=].file), label: \([=14=].label)"}))
    movies = response.result.movies
} catch {
    print(error)
}