简体   繁体   English

如何在 swift 4 中解析 Json 字典

[英]How to Parse Json dictonary in swift 4

Hi I have a problem with this Json:嗨,我对这个 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"
        }]
    }
}

When I parse Json in swift 5 with this code当我使用此代码在 swift 5 中解析 Json 时

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

I get this error我收到这个错误

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)):表达式意外引发错误:Swift.DecodingError.typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary 相反。",underlyingError: nil)):

How can I solve this?我该如何解决这个问题?

For the below JSON,对于下面的 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"}]}}

The Codable models that you need to use,您需要使用的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
}

Parse the JSON data like so,像这样解析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)
}

Edit:编辑:

To save the movies separately, create a variable of type [Movie],要单独保存电影,请创建一个类型为 [Movie] 的变量,

var movies = [Movie]()

Now, while parsing save the response.result.movies in the above created property,现在,在解析时将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