Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

json - Decoding Error -- Expected to decode Dictionary<String, Any> but found an array instead

I am new to swift programming and Xcode and am try to call mysql data from the database to Xcode using Json encoding. I was able to successfully call all the data (array) but when I decide to call only one value(column) say Courses.name I get the "Decoding Error -- Expected to decode Dictionary but found an array instead." How do I work my way around this problem? My goal is to print only courses.name

import UIKit

struct Course: Decodable {
let id: String
let name: String
let member:  String

 }

class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    let jsonUrlString = "http://oriri.ng/aapl/service.php"
    guard let url = URL(string: jsonUrlString) else
    { return }

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

        guard let data =  data else{ return }

        do {

            let courses = try JSONDecoder().decode(Course.self, from: data)
            print(courses.name)


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

    }.resume()

   }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

[{"id":"1","name":"sobande_ibukun","member":"blue"}]

The [] around denotes that it is an array. Decode with the following and it should work:

let courses = try JSONDecoder().decode([Course].self, from: data)

If you are sure that it will always be one course you can do:

print(courses.first!.name)

If there may be many courses you can print every name:

courses.forEach { course in print(course.name) }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...