Swift JSON解析,没有JSON对象的标题



所以我有一个很难解决的问题。我的JSON代码具有相当奇怪的结构。它具有以下结构:

{
    "title": [
        [
            "Temperature",
            "9 u00b0C (283 u00b0F)",
            "Good"
        ],
        [
            "Visibility",
            "10 KM (6.2 Mi)",
            "Good"
        ]
    ]
}

使用以下代码,我能够打印出一些简单的JSON代码:

import UIKit
struct WeatherItem: Decodable {
    let title: String?
    let value: String?
    let condition: String?
}
class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        let jsonUrlString = "http://somelinkhere"
        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 weather = try JSONDecoder().decode(WeatherItem.self, from: data)
                print(weather.title)
            } catch let jsonErr{
                print("error", jsonErr)
            }
        }.resume()
    }
}

但问题是我对所有3个变量,标题,价值和条件nil的输出。我确定我必须更改结构代码,但我不知道什么方式。

我如何进入没有标题的JSON代码?

您必须自己编写解码初始器:

struct WeatherData: Decodable {
    let title: [WeatherItem]
}
struct WeatherItem: Decodable {
    let title: String?
    let value: String?
    let condition: String?
    public init(from decoder: Decoder) throws {
        // decode the value for WeatherItem as [String]         
        let container = try decoder.singleValueContainer()
        let components = try container.decode([String].self)
        title = components.count > 0 ? components[0] : nil
        value = components.count > 1 ? components[1] : nil
        condition = components.count > 2 ? components[2] : nil
    }
}
let json = """
{
  "title": [
     ["Temperature", "9", "Good"],
     ["Visibility", "10 KM (6.2 Mi)", "Good"]
   ]
}
"""
let jsonData: Data = json.data(using: .utf8)!
let decoder = JSONDecoder()
let decoded = try! decoder.decode(WeatherData.self, from: jsonData)
debugPrint(decoded)

正确JSON

{
    "title": [
        [
            "Temperature",
            " ",
            "Good"
        ],
        [
            "Visibility",
            "10 KM (6.2 Mi)",
            "Good"
        ]
    ]
}

var arr = [WeatherItem]()
do {
     let res = try JSONDecoder().decode([String:[[String]]].self, from: data)
     let content = res["title"]!
     content.forEach {
       if $0.count >= 3 {
         arr.append(WeatherItem(title:$0[0],value:$0[1],condition:$0[2]))
       }
     }
     print(arr)
} catch {
  print(error)
}

讨论:您的root对象是一个字典,包含1个名为 title的键,它的值是一系列字符串或模型逻辑中的数组,它是一个名为WeatherItem的模型数组适当地为其结构,因此使用此

let weather = try JSONDecoder().decode(WeatherItem.self, from: data)

无法使用,因为当前的JSON不包含键valuecondition

适当的曲折将是

[
    {
        "title":"Temperature" ,
        "value":"",
        "condition":"Good"
    },
    {
        "title":"Visibility",
        "title":"10 KM (6.2 Mi)",
        "condition":"Good"
    }
]

这将使您能够做

let weather = try JSONDecoder().decode([WeatherItem].self, from: data)

相关内容

  • 没有找到相关文章

最新更新