首页 > 解决方案 > 快速 JSON 错误字典?我该怎么办

问题描述

所以我试图在我的 swift IOS 应用程序上获取正在播放的信息。

数据看起来像这样

{"data":[{"track":{"_id":"5dd87773c125b904113d7d39","partnerId":"DRN1","title":"Not Giving Up (Nu Disco Mix)","artist":"HP Vince & Dave Leatherman","album":"Disc 2: Traxsource \"Nu Disco & Indie Dance\"","website":"","imageurl":"http://covers.drn1.com.au/az_B1017221_Disc 2 Traxsource Nu Disco & Indie Dance_HP Vince & Dave Leatherman.jpg","datetime":"2019-11-23T00:04:03.245Z","__v":0}}]}

但是当我运行时出现此错误

nw_endpoint_flow_copy_multipath_subflow_counts Called on non-Multipath connection
error json  typeMismatch(Swift.Array<Any>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "track", intValue: nil)], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil))

我的代码

struct nowplayng: Decodable{
    let data: [data]
}

struct data: Decodable{
    let track: [trackinfo]
}
struct trackinfo: Decodable {
    let title: String
    let artist: String
    let imageurl: String
}



override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let jsonURLString = "https://api.drn1.com.au/station/playing"
        guard let feedurl = URL(string: jsonURLString) else { return }

        URLSession.shared.dataTask(with: feedurl) { (data,response,err)
            in

            guard let data = data else { return }

            do{
                let nowplaying = try JSONDecoder().decode(nowplayng.self, from: data)
                print(nowplaying.data)

            }catch let jsonErr{
            print("error json ", jsonErr)
            }

//            let dataAsString = String(data:data, encoding: .utf8)
//            print(dataAsString)
        }.resume()



    }

标签: iosjsonswiftdictionary

解决方案


替换(track键是字典而不是数组)

let track: [Trackinfo]

let track:Trackinfo

推荐阅读