如何在 swift 4 中解析 Json 字典

塞斯科88

嗨,我对这个 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)):

我该如何解决这个问题?

PGD​​ev

对于下面的 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)
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章