简体   繁体   English

解析 JSON、iOS、Swift4

[英]parse JSON, iOS, Swift4

I am trying to parse some json but seem to be getting nil in the outputs.我正在尝试解析一些 json,但输出中似乎为零。

I am not sure where I am going wrong and could use some help trying to figure this out.我不确定我哪里出错了,可以使用一些帮助来解决这个问题。

struct albumInfo: Decodable {
var name: String?
var artist: String?
var url: String?
var playcount: String?
var listeners: String?
var releasedate: String?
var summary: String?
}   


class SearchVC: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()


    Choice = "album"
    Album = "Believe"
    Artist = "Cher"

    let tryURL = "\(BASE_URL)\(Choice!).getinfo&api_key=\(API_KEY)&artist=\(Artist!)&album=\(Album!)&format=json"
    print(tryURL)

    guard let url = URL(string: tryURL) else { return }


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

        guard let data = data else { return }

            do {
            let albumDescription = try JSONDecoder().decode(albumInfo.self, from: data)

                print(albumDescription.artist)

            }catch let jsonErr {
                print("Error seroalizing json", jsonErr)
        }
    }.resume()

}

Here is the data as shown with the tryUrl.这是与 tryUrl 一起显示的数据。

在此处输入图片说明

First of all please conform to the naming convention that struct names start with a capital letter.首先请遵守结构名称以大写字母开头的命名约定。

There are two major issues:有两个主要问题:

  1. The root object is a dictionary with one key album containing the dictionary with keys name , listeners etc.根对象是一个带有一个键album的字典,其中包含带有键namelisteners等的字典。
  2. The key summary is in another dictionary for key wiki .关键summary在关键wiki另一个字典中。

The structure of the JSON is very easy to identify. JSON 的结构很容易识别。 The body within each pair of braces ( {} ) represents a separate struct.每对大括号 ( {} ) 内的主体代表一个单独的结构。

Further there is no key releasedate so this struct member has to be declared as optional, all other members can be declared as non-optional and as constants ( let ).此外,没有键releasedate因此必须将此结构成员声明为可选,所有其他成员都可以声明为非可选和常量( let )。 url can be declared as URL for free. url可以免费声明为URL

Change your structs to将您的结构更改为

struct Root : Decodable {
    let album : AlbumInfo
}

struct AlbumInfo: Decodable {
    let name: String
    let artist: String
    let url: URL
    let playcount: String
    let listeners: String
    let releasedate: String?
    let wiki : Wiki
}   

struct Wiki: Decodable {
    let content: String     
    let published: String
    let summary: String
}

and decode Root并解码Root

let albumDescription = try JSONDecoder().decode(Root.self, from: data)
print(albumDescription.album.artist)

您响应的第一个键是“相册”,您需要先解析它。

The classes do not correspond to json, I guess you should use the following approach (new classes implement your decode, encode protocol):这些类与 json 不对应,我想您应该使用以下方法(新类实现您的解码、编码协议):

class JsonInfo {
var album : albumInfo
}

do {
let albumDescription = try JSONDecoder().decode(albumInfo.self, from: data)

print(albumDescription.album.artist)

}catch let jsonErr {
print("Error seroalizing json", jsonErr)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM