发布
社区首页 >问答首页 >数组解析中的JSON数组,SWIFTYJson

数组解析中的JSON数组,SWIFTYJson
EN

Stack Overflow用户
提问于 2018-06-15 05:12:24
回答 3查看 635关注 0票数 3

我一直在学习SWIFT应用程序中的JSON解析。到目前为止,我一直在使用一个简单的免费API,没有任何问题,应用程序按设计工作。但是现在我正在调用一个API,它在数组中返回一个数组。我已经按照指示读取并准备了变量来访问元素,但是SWIFT仍然看不到返回的JSON中的任何数据。我在这方面已经挣扎了2天,改变了我在网上所能找到的所有想法,但是我的默认变量仍然没有被来自JSON的数据覆盖。使用豆荚SWIFTYJson。

JSON部分摘录:

代码语言:javascript
代码运行次数:0
复制
    {
  "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
        }
      ],

处理它的代码:

代码语言:javascript
代码运行次数:0
复制
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)")

输出到控制台的变量与默认值保持不变:

代码语言:javascript
代码运行次数:0
复制
TEST variable 1: 0
TEST variable 2: 0
TEST variable 3: 0
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-06-15 05:20:05

你用错误的方式解析数据。

json["list"]只是JSON对象而不是数组对象,所以如何通过使用[0]传递索引。

这一问题应按以下解决办法加以纠正。

代码语言:javascript
代码运行次数:0
复制
weatherDataModel.weatherTest1 = json["list"].arrayValue[0]["weather"].arrayValue[0]["id"].intValue
票数 1
EN

Stack Overflow用户

发布于 2018-06-15 06:22:10

在当前版本的SwiftyJSON中,您正在使用的初始化器上的注释如下:

代码语言:javascript
代码运行次数:0
复制
/**
 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清楚地表示:

代码语言:javascript
代码运行次数:0
复制
"list" : [
    {

[表示它是一个数组,所以我不确定最初是哪里出了问题。如果有人遇到了同样的问题,并使用init(JSON)解析具有当前版本的SwiftyJSON的对象,我将在这里留下这个答案。

票数 0
EN

Stack Overflow用户

发布于 2018-06-25 09:00:15

如果您正在学习如何在Swift中解析,则必须学习如何构造模型以正确解析JSON。

(顺便说一句,如果您使用Swift 4,不需要使用SWIFTYJson,请在这里了解更多信息:https://benscheirman.com/2017/06/swift-json/)

如果要使用SWIFTYJson,请举一个示例:

代码语言:javascript
代码运行次数:0
复制
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也这样做

在得到所有模型之后,可以在请求中解析它:

代码语言:javascript
代码运行次数:0
复制
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")
            }
        }
 }

然后,您将在方法中找到已经解析的数据对象:

代码语言:javascript
代码运行次数:0
复制
func updateWeatherData(data: WeatherDataModel) {
    // exemple
    print(data.list[0].weather[0].id) // = 800
}

希望它能帮到你。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50869448

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档