如何将多个嵌套的JSON响应解析为数组?

时间:2016-07-21 11:14:49

标签: arrays json swift parsing

我想投出我的JSON响应,但它会抛出错误。我不知道如何正确解析JSON以使字段可访问。 我怎样才能做到这一点?

 func cellButtonTapped(sender: AnyObject) {

    self.restApi.getSchoolDetails(schoolId) {responseObject, error in
        // use responseObject and error here

         self.schoolDetailsCollection = NSDictionary(dictionary: responseObject! as! [NSObject : AnyObject])

        //access the inner array from the json answer called result
      self.schoolDetailsList = self.schoolDetailsCollection["result"] as! [[String:AnyObject]]

        print(self.schoolDetailsCollection)

       print(self.schoolDetailsList)


    }

}

此行引发以下错误:

self.schoolDetailsList = self.schoolDetailsCollection["result"] as! [[String:AnyObject]]

错误:

  

无法转换类型' __ NSCFDictionary'的值(0x102f3a178)到NSArray' (0x102f39b88)。

Json: -

 result =     {
    address = " 379 Hay St, Perth WA 6000, Australia";
    city = "Perth ";
    "cou_id" = AU;
    "cur_id" = "";
    environment = L;
    financed = "<null>";
    images =         (
        "Milner_college_3.jpeg",
        "Milner_college_2.jpeg.png",
        "Milner_college_4.jpeg"
    );
    intro = "Our language school is one of the most famous in Australia with over 30 years of experience of English teaching. It is situated in the middle of Perth, surrounded by shops, caf\U00e9s and restaurants. The train station can be reached in just a couple of minutes by walking. There is a free shuttle bus with a stop right in front of the school. <br/>The school has 30 classrooms with air-condition, a spacious student lounge, a computer room, a library, a caf\U00e9, a kitchen and a gaming room. Free Wi-Fi covers the whole area. During the breaks, students can meet in the 200m2 garden and can chill out and chat under umbrellas. Highly qualified teachers ensure your progress by providing you a great learning experience.";
    leisure = "";
    name = "Milner college";
    "sco_id" = 3;
    "sco_type" = LS;
    "sell_point" = "* Provide our students with the best possible standard of teaching.<br/>* Give our students an enjoyable and fulfilling overall experience.<br/>* Give our students value for the money they pay us.<br/>* Work as a team, in which our teachers and other staff trust and support each other.<br/>* Maintain high standards, striving always to improve them.<br/>* Enable our students, by enhancing their language skills to achieve great things.<br/>* Be mindful that we have a duty beyond being an ethical and competent college, by doing some good for humanity.";
    "video_url" = "<null>";
    "web_url" = "https://www.milner.wa.edu.au/";
};
}

1 个答案:

答案 0 :(得分:1)

检查if let块以转换响应对象并解析它。

if let response = responseObject as? NSDictionary {
  self.schoolDetailsList = response as? NSDictionary
  if let address = response["result"]["address"] as? String {
     print(address) // 379 Hay St, Perth WA 6000, Australia
  }
}