0

I checked this tutorial https://www.hackingwithswift.com/forums/swiftui/nested-json/4018 to fix a nested json issue.

My JSON source has changed from

[{"title":"title","link":"...","description":"...".... 

to

{"items":[{..

my original struct was like this

struct Novitads: Codable, Identifiable {
    public var id = UUID()
    public var title: String
    public var pubDate: String
    public var description: String
    public var link: String
    public var image: URL
//    public var pubDate: String
}

now I added:

struct News: Codable {
    var items: [Novitads]
}

which is consistent with the article with the solution.

Unfortunately, my fetch class now fails:

class FetchNovitads: ObservableObject {

@Published var Novitadss = [Novitads]()
@Published var selectedCode: String?
public lazy var selectC: Double = 0.1

let x: Double = 21.25
func refresh() {
    let url = URL(string: "https://testapi-")!
    print (url)
    print (selectedCode)
    print (selectC)
    
    selectC = Double(selectedCode ?? "0") ?? 0.1
    
    URLSession.shared.dataTask(with: url) { data, _, _ in
        do {
            if let NovitadsData = data {
           
                let decodedData = try JSONDecoder().decode(News.self, from: NovitadsData)
                DispatchQueue.main.async {
                    
                    self.Novitadss = decodedData
                }
            } else {
                print("No data")
            }
        } catch {
            print(error)
        }
    }.resume()
}

}

more precisely on self.Novitadss = decodedData Cannot assign value of type 'News' to type '[Novitads]' this did not occur when I used the previous json structure (not nested) so had no need for the News struct.

I am sure there is something trivial I am missing :)

2 Answers 2

1

If you decode News you have to assign the items array to Novitadss

self.Novitadss = decodedData.items

And please name properties with starting lowercase letter

Sign up to request clarification or add additional context in comments.

Comments

1

Use

self.Novitadss = decodedData.items 

and now by iterating, you can fetch the properties inside this with respect to index value.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.