选择JSON数组

时间:2017-12-03 18:25:38

标签: ios arrays swift

我想从这个JSON中选择subject数组。

[
    {
        "program_id": "1",
        "program": "O levels",
        "subjects": [
            {
                "program_id": "1",
                "program": null,
                "subject_id": "1",
                "subject_code": "4037",
                "subject_name": "Add-Maths",
                "subject_image": ""
            }
      ]
}

这是我的代码。

for result in json["programs"].array! {                         
    let json2 = JSON( result["subjects"].arrayValue)
    let type = json2["program_id"].arrayValue
    let type1 = json2["program_id"].stringValue
    self.collectionarray1.append(Explore_model_for_collectionview.init( 
        Explore_program_id: json2["program_id"].stringValue,
        Explore_program: json2["program"].stringValue,
        Explore_subject_id: json2["subject_id"].stringValue,
        Explore_subject_code: json2["subject_code"].stringValue,
        Explore_subject_name: json2["subject_name"].stringValue,
        Explore_subject_image: json2["subject_image"].stringValue))

1 个答案:

答案 0 :(得分:0)

if let results = json as? [[String:AnyObject]]{

    for result in results  {

       if let subjects = result["subjects"] as? [[String: AnyObject]]{

           for subject in subjects  {
              let type = subject["program_id"] as? String ?? ""
              // now in the same way, you can parse all the values.
             }
        }
    }
}

你可以解析上面的JSON数据。这将是一个好方法。   一切顺利。