所以我遇到了一个非常棘手的问题。我的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代码?
答案 0 :(得分:1)
更正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)
}
讨论:您的根对象是一个字典,其中包含一个名为title
的键,其值是一个字符串数组数组,或者从模型逻辑中它是一个名为{ {1}},但结构不正确,因此使用
WeatherItem
不起作用,因为当前json不包含键let weather = try JSONDecoder().decode(WeatherItem.self, from: data)
和value
合适的结构是
condition
这将使您能够做到
[
{
"title":"Temperature" ,
"value":"",
"condition":"Good"
},
{
"title":"Visibility",
"title":"10 KM (6.2 Mi)",
"condition":"Good"
}
]
答案 1 :(得分:1)
您将必须自己编写解码初始化程序:
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)