【问题标题】:How to parse particular JSON file in SwiftUI如何在 SwiftUI 中解析特定的 JSON 文件
【发布时间】:2021-10-12 19:22:03
【问题描述】:

假设我正在尝试使用 SwiftUI 解析这个特定的 JSON 文件:

data.json

[
    {
        "number": 1,
        "word": "hello",
        "sentence": {
            "word_one": "my",
            "word_two": "name"
            "word_three": "is"
            "word_four": "jeff"
        }
    },
    {
        "number": 2,
        "word": "there",
        "sentence": {
            "word_one": "i",
            "word_two": "dream"
            "word_three": "about"
            "word_four": "cheese"
        }
    }
]

我了解如何解析 numberword,但我遇到的问题是如何解析 sentence 中的所有内容。我是 iOS 编程新手,我一直在寻找的资源让我感到困惑。这是我到目前为止的代码:

struct Content: Codable, Hashable {
    let number: Int
    let word: String
}

struct ContentView: View {
    func jsonParse() -> [Content] {
            let url = Bundle.main.url(forResource: "data", withExtension: "json")!
            let data = try! Data(contentsOf: url)
            let decoder = JSONDecoder()
            let products = try? decoder.decode([Content].self, from: data)
            return products!
        }
    
    var body: some View {
        NavigationView {
            List {
                ForEach(jsonParse(), id: \.self) { content in
                    VStack(alignment: .leading, spacing: 0) {
                        Text("\(content.word)")
                    }
                }
            }
        }
    }
}

感谢您的帮助!

【问题讨论】:

  • 你的 JSON 数据包含两个字典,不是数字和单词。
  • @ElTomato 我的结构有什么问题吗?
  • 您可以将sentence 声明为字典[String:String]
  • @Paulw11 我如何在ContentView 上创建带有sentence 的文本?会不会是 Text("\(content.sentence.word_one)") 之类的东西?
  • 不,您需要获取字典的keys 并对数组进行排序,然后在排序后的数组上迭代键并访问值for key in dictionary.keys.sorted { Text(dictionary[key]) 之类的东西;我会将键和排序放在模型中的计算变量后面并使用ForEach

标签: ios json swift swiftui


【解决方案1】:

首先,您的 JSON 数据无效。应该是这样的。

[
    {
        "number": 1,
        "word": "hello",
        "sentence": {
            "word_one": "my",
            "word_two": "name",
            "word_three": "is",
            "word_four": "jeff"
        }
    },
    {
        "number": 2,
        "word": "there",
        "sentence": {
            "word_one": "i",
            "word_two": "dream",
            "word_three": "about",
            "word_four": "cheese"
        }
    }
]

没有。 2、读取你的数据如下。

import UIKit

struct Content: Decodable {
    let number: Int
    let word: String
    let sentence: Sentence
}

struct Sentence: Decodable {
    let word_one: String
    let word_two: String
    let word_three: String
    let word_four: String
}

最后,按如下方式读取包中的 JSON 文件。

if let path = Bundle.main.path(forResource: "jsonData14", ofType: "json") {
   if let jsonData = readFileContent(path: path) {
      do {
         let result = try JSONDecoder().decode([Content].self, from: jsonData)
         print(result)
         
         } catch let error as NSError {
         print("\(error)")
      }
   }
}

【讨论】:

    【解决方案2】:

    您好,El Tomato 指出您的 JSON 无效。我使用了 El Tomato 提供的固定 JSON。

    如果你只是想在这里得到答案。

    import SwiftUI
    
    struct ContentView: View {
        let json = """
    [
        {
            "number": 1,
            "word": "hello",
            "sentence": {
                "word_one": "my",
                "word_two": "name",
                "word_three": "is",
                "word_four": "jeff"
            }
        },
        {
            "number": 2,
            "word": "there",
            "sentence": {
                "word_one": "i",
                "word_two": "dream",
                "word_three": "about",
                "word_four": "cheese"
            }
        }
    ]
    """.data(using: .utf8)!
        var body: some View {
            Text("Hello, world!")
                .padding()
                .onAppear(perform: decode)
        }
        
        func decode() {
            let decoder = JSONDecoder()
            
            do {
                let result = try decoder.decode(Content.self, from: json)
                print(result)
            } catch {
                print(error)
            }
            
        }
    }
    
    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }
    
    // MARK: - ContentElement
    struct ContentElement: Codable {
        let number: Int
        let word: String
        let sentence: Sentence
    }
    
    // MARK: - Sentence
    struct Sentence: Codable {
        let wordOne, wordTwo, wordThree, wordFour: String
        
        enum CodingKeys: String, CodingKey {
            case wordOne = "word_one"
            case wordTwo = "word_two"
            case wordThree = "word_three"
            case wordFour = "word_four"
        }
    }
    
    typealias Content = [ContentElement]
    

    我使用了一个名为quicktype 的程序,它预先填充了解码 JSON 所需的结构。很抱歉,我无法进一步解释,因为我也不知道。

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 2019-05-03
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多