首页 > 解决方案 > 如何在 SwiftUI 中将本地 JSON 文件解析为 ListView?这里是应用程序开发的新手

问题描述

我似乎无法解析我在 SwiftUI 中为一个简单的应用程序创意创建的本地 JSON 文件,而且我是应用程序开发的新手。我尝试了一些方法,但没有奏效。试图找出我在解析中遗漏的任何内容并将其放入 ListView。我要做的是解析语言和句子,在这种情况下,我的 3 个对象中的句子包含我要解析的不同数量的句子,例如 sentence1、sentence1b 等。(编辑:向您展示两个不同的代码错误和 Json 片段)

  1. JSON 文件片段
[
    {
    "name": "English",
    "id": 1,
    "sentence": {
        "sentence1": "I eat the apple",
        "sentence2": "It is John's apple",
        "sentence3": "I give John the apple",
        "sentence4": "We give him the apple",
        "sentence5": "He gives it to John",
        "sentence6": "She gives it to him",
        "sentence7": "Is the apple red?",
        "sentence8": "The apples are red",
        "sentence9": "I must give it to him",
        "sentence10": "I want to give it to her",
        "sentence11": "I'm going to know tomorrow",
        "sentence12": "I can't eat the apple"
    }
},
{
    "name": "Mandarin",
    "id": 2,
    "sentence": {
        "sentence1": "我吃的苹果",
        "sentence1a": "我吃的蘋果",
        "sentence1b": "Wǒ chī de píngguǒ",
        "sentence2": "之是约翰的苹果",
        "sentence2a": "之是約翰的蘋果",
        "sentence2b": "Zhī shì Yuēhàn de píngguǒ",
        "sentence3": "我给约翰的苹果",
        "sentence3a": "我給約翰的蘋果",
        "sentence3b": "Wǒ gěi Yuēhàn de píngguǒ",
        "sentence4": "我们给约翰的苹果",
        "sentence4a": "我們給約翰的蘋果",
        "sentence4b": "Wǒ men gěi Yuēhàn de píngguǒ",
        "sentence5": "他把它交给约翰",
        "sentence5a": "他把它交給約翰",
        "sentence5b": "Tā bǎ tā jiāo gěi Yuēhàn",
        "sentence6": "她给了它",
        "sentence6a": "她給了它",
        "sentence6b": "Tā gěi le tā",
        "sentence7": "苹果是红色的吗?",
        "sentence7a": "蘋果是紅色的嗎?",
        "sentence7b": "Píngguǒ shì hóngsè de ma?",
        "sentence8": "苹果是红色的",
        "sentence8a": "苹果是红色的",
        "sentence8b": "Píngguǒ shì hóngsè de",
        "sentence9": "我必须给他",
        "sentence9a": "我必須給他",
        "sentence9b": "Wǒ bìxū gěi tā",
        "sentence10": "我想给他",
        "sentence10a": "我想給他",
        "sentence10b": "Wǒ xiǎng gěi tā",
        "sentence11": "我明天要知道",
        "sentence11a": "我明天要知道",
        "sentence11b": "Wǒ míngtiān yào zhīdào",
        "sentence12": "我不吃的苹果",
        "sentence12a": "我不吃的蘋果",
        "sentence12b": "Wǒ bù chī de píngguǒ"
    }
},
{
    "name": "French",
    "id": 3,
    "sentence": {
        "sentence1": "Je mange la pomme",
        "sentence2": "C’est la pomme de John",
        "sentence3": "Je donne la pomme à John",
        "sentence4": "On lui donne la pomme",
        "sentence5": "Il la donne à John",
        "sentence6": "Elle la lui donne",
        "sentence7": "Est-ce que la pomme est rouge? or Elle est rouge, la pomme?",
        "sentence8": "Les pommes est rouges",
        "sentence9": "Je dois la lui donner",
        "sentence10": "Je veux la lui donner",
        "sentence11": "Je le saurai demain",
        "sentence12": "Je ne peux pas manger la pomme"
    }
}
]
  1. 尝试错误 1 ​​- 使用 UIKit
struct AppData: Codable {

    var name: String
    var id: Int
    var sentence: String
}

public class DataLoader {

    @Published var appData = [AppData]()

    init() {
        load()
        sort()
    }

    func load() {

        if let fileLocation = Bundle.main.url(forResource: "twelveData", withExtension: "json") {

            // do catch in case of error
            do {
                let data = try Data(contentsOf: fileLocation)
                let jsonDecoder = JSONDecoder()
                let dataFromJson = try JSONDecoder.decode([AppData].self, from: data)

                self.appData = dataFromJson
            } catch {
                print(error)
            }
        }
    }
    func sort(){
        self.appData = self.appData.sorted(by: {$0.id < $1.id})
    }
}
  1. 尝试错误 2
import SwiftUI
import Foundation
import Combine

struct TwelveData: Codable, Identifiable {
    public var id: Int
    public var name: String
    public var sentence: String

    enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "language"
        case sentence = "sentence"
    }
}

class TwelveSentences: ObservableObject {
    @Published var twelveData = [TwelveData]()

    init() {
        guard let path = Bundle.main.url(forResource: "twelveData", withExtension: "json") else { return }
        do {
            let data = try Data(contentsOf: path)
            DispatchQueue.main.async {
                self.twelveData = try JSONDecoder().decode([TwelveData].self, from: data)
            }
        } catch {
            print("error:\(error)")
        }
    }
}

struct ContentView: View {
    @ObservedObject var fetch = TwelveData()

    var body: some View {
        NavigationView {
            List(fetch.TwelveData) { TwelveData in
                VStack {
                    Text(TwelveData.name)

            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
}

标签: iosswiftparsinglistviewswiftui

解决方案


你需要先解析

class FecthYourObject: ObservableObject {

    @Published var yourObjects = [YourObject]()

    init() {
        guard let path = Bundle.main.url(forResource: "local_file", withExtension: "json") else { return }
        do {
            let data = try Data(contentsOf: path)
            DispatchQueue.main.async {
                self.yourObjects = try JSONDecoder().decode([YourObject].self, from: data)
            }
        } catch {
            print("error:\(error)")
        }
    }
}

然后

struct ContentView: View {
    @ObservedObject var fetch = FetchYourObject()

    List(fetch.yourObjects) { obj in
      ...
    }
}

推荐阅读