1

I would like to parse/decode a JSON string and then create a dynamic list.

Example JSON: [{"course":"course1","teacher":"teacherName1"},{"course":"course1","teacher":"teacherName2"}]

My wish:

List {
  HStack {
    Text("course1")
    Spacer()
    Text("teacherName1")
  }
  HStack {
    Text("course2")
    Spacer()
    Text("teacherName2")
  }
}

I've tried it with JSONDecoder() and arrays but Xcode marks my TabView over and over with this message: Cannot convert value of type 'Binding<Int>' to expected argument type 'Binding<_>?'

I'm new to swift, sorry ;)

1
  • 1
    show us, what did you try! How could somebody to help you with your code, if it is not part of your question? Commented Feb 14, 2020 at 21:02

1 Answer 1

3

I made an example that you can follow:

import SwiftUI

let jsonString = """
[{"course":"course1","teacher":"teacherName1"},{"course":"course1","teacher":"teacherName2"}]
"""

let data = jsonString.data(using: .utf8) ?? Data()


struct Course: Codable, Identifiable {

    let id = UUID()
    let course: String
    let teacher: String
}

struct ContentView: View {

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

    var body: some View {
        List(courses) { course in
            HStack {
                Text(course.course)
                Spacer()
                Text(course.teacher)
            }
        }
    }
}

I made the Course struct confirm to Identifiable as well as Codable so that the List can iterate over the array of courses. Also I defaulted to empty Data and empty courses array in case decoding fails. You could write better error handling here depending on your needs.

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

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.