简体   繁体   中英

parse JSON, iOS, Swift4

I am trying to parse some json but seem to be getting nil in the outputs.

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.

在此处输入图片说明

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.
  2. The key summary is in another dictionary for key wiki .

The structure of the JSON is very easy to identify. 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 ). url can be declared as URL for free.

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

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):

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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