我一直在学习SWIFT应用程序中的JSON解析。到目前为止,我一直在使用一个简单的免费API,没有任何问题,应用程序按设计工作。但是现在我正在调用一个API,它在数组中返回一个数组。我已经按照指示读取并准备了变量来访问元素,但是SWIFT仍然看不到返回的JSON中的任何数据。我在这方面已经挣扎了2天,改变了我在网上所能找到的所有想法,但是我的默认变量仍然没有被来自JSON的数据覆盖。使用豆荚SWIFTYJson。
JSON部分摘录:
{
"list" : [
{
"main" : {
"grnd_level" : 984.67999999999995,
"temp_min" : 283.30000000000001,
"temp_max" : 284.54599999999999,
"temp" : 283.30000000000001,
"sea_level" : 1022.5,
"pressure" : 984.67999999999995,
"humidity" : 88,
"temp_kf" : -1.25
},
"clouds" : {
"all" : 0
},
"weather" : [
{
"main" : "Clear",
"icon" : "01n",
"description" : "clear sky",
"id" : 800
}
],
处理它的代码:
func getWeatherData(url: String, parameters: [String : String]){
//make http request and handle the JSON response
print("\(url)\(parameters)")
Alamofire.request(url, method: .get, parameters: parameters).responseJSON {
response in //in means you are inside a closure (function inside a function)
if response.result.isSuccess {
print("Successfully got the weather data!")
let weatherJSON : JSON = JSON(response.result.value!) //saving the JSON response to a constant weathrJSON . We are using ! to self unwrap the value.
self.updateWeatherData(json: weatherJSON) //func to parse our json from API. Self tells the compiler to look for the method inside the current class
print(weatherJSON)
} else {
self.cityName.text = "Unable to fetch weather - please check active connection."
}
}
}
func updateWeatherData(json: JSON) {
(...)
//parse JSON for weather forecast day 1
weatherDataModel.weatherTest1 = json["list"][0]["weather"][0]["id"].intValue
//parse JSON for weather forecast day 2
weatherDataModel.weatherTest2 = json["list"][8]["weather"][0]["id"].intValue
//parse JSON for weather forecast day 3
weatherDataModel.weatherTest3 = json["list"][16]["weather"][0]["id"].intValue
print("TEST variable 1: \(weatherDataModel.weatherTest1)")
print("TEST variable 2: \(weatherDataModel.weatherTest2)")
print("TEST variable 3: \(weatherDataModel.weatherTest3)")
输出到控制台的变量与默认值保持不变:
TEST variable 1: 0
TEST variable 2: 0
TEST variable 3: 0
发布于 2018-06-15 05:20:05
你用错误的方式解析数据。
json["list"]
只是JSON对象而不是数组对象,所以如何通过使用[0]
传递索引。
这一问题应按以下解决办法加以纠正。
weatherDataModel.weatherTest1 = json["list"].arrayValue[0]["weather"].arrayValue[0]["id"].intValue
发布于 2018-06-15 06:22:10
在当前版本的SwiftyJSON中,您正在使用的初始化器上的注释如下:
/**
Creates a JSON object
- note: this does not parse a `String` into JSON, instead use `init(parseJSON: String)`
- parameter object: the object
- returns: the created JSON object
*/
因此,您应该使用let weatherJSON : JSON = JSON(response.result.value!)
而不是let weatherJSON : JSON = JSON(parseJSON: response.result.value!)
之后,基于JSON,我认为您当前的代码应该可以工作。
编辑
我知道选择的另一个答案是json"list“是一个JSON对象,而不是一个数组,但是摘录中显示的JSON清楚地表示:
"list" : [
{
[
表示它是一个数组,所以我不确定最初是哪里出了问题。如果有人遇到了同样的问题,并使用init(JSON)解析具有当前版本的SwiftyJSON的对象,我将在这里留下这个答案。
发布于 2018-06-25 09:00:15
如果您正在学习如何在Swift中解析,则必须学习如何构造模型以正确解析JSON。
(顺便说一句,如果您使用Swift 4,不需要使用SWIFTYJson,请在这里了解更多信息:https://benscheirman.com/2017/06/swift-json/)
如果要使用SWIFTYJson,请举一个示例:
struct WeatherDataModel {
var list = [ListModel]?
init() {
self.list = []
}
init(json: [String: Any]) {
if let object = json["list"] as? [[String: Any]] {
for listJson in object {
let list = ListModel(json: listJson)
self.list.append(list)
}
}
}
}
struct ListModel {
var main : Main?
var clouds : Clouds?
var weather : [Weather]?
init() {
self.main = Main()
self.clouds = Clouds()
self.weather = []
}
init(json: [String: Any]) {
if let mainJson = json["main"] as? [String: Any] {
self.main = MainModel(json: mainJson)
}
if let cloudsJson = json["clouds"] as? [String: Any] {
self.clouds = CloudsModel(json: cloudsJson)
}
if let objectWeather = json["weather"] as? [[String: Any]] {
for weatherJson in objectWeather {
let weather = WeatherModel(json: weatherJson)
self.weather.append(weather)
}
}
}
}
对MainModel,CloudsModel,WeatherModel也这样做
在得到所有模型之后,可以在请求中解析它:
Alamofire.request(url, method: .get, parameters: parameters).validate().responseJSON { (response) -> Void in
if let value = response.data {
do {
let json = try JSON(data: data)
if let dictionnary = json.dictionnaryObject {
let object = WeatherDataModel(json: dictionnary)
self.updateWeatherData(data: object)
}
} catch {
print("cannot convert to Json")
}
}
}
然后,您将在方法中找到已经解析的数据对象:
func updateWeatherData(data: WeatherDataModel) {
// exemple
print(data.list[0].weather[0].id) // = 800
}
希望它能帮到你。
https://stackoverflow.com/questions/50869448
复制相似问题