代码之家  ›  专栏  ›  技术社区  ›  Stella

Swift JSON提取

  •  -1
  • Stella  · 技术社区  · 9 年前

    我正在开发一个swift iOS应用程序,并从web服务获得以下JSON响应。我试图解析并获取 nextResponse

    listofstudents:
            ({
            studentsList =     (
                        {
                    data =             (
                        "32872.23",
                        "38814.87",
                        "38915.85"
                    );
                    label = “name, parents and guardians”;
                }
            );
            dateList =     (
                "Apr 26, 2017",
                "Jun 10, 2017",
                "Jul 26, 2017"
            );
            firstResponse = “This school has 1432 students and 387 teachers.”;
            nextResponse = “This school has around 1400 students.”;
        })
    

    银行代码:

        do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                    print("json: \(json)")
    
                    if let parseJSON = json {
    
                        let finalResponse = parseJSON["listofstudents"] as? AnyObject
                        print("listofstudents::   \(finalResponse)")
    
                        let nextResponse = parseJSON["nextResponse"] as? AnyObject
                        print("nextResponse::   \(nextResponse)")
             }
                } catch {
                    print(error)
                }
    
    3 回复  |  直到 9 年前
        1
  •  3
  •   Dávid Pásztor    9 年前

    不要使用 NSDictionary 在Swift中,但使用其本地Swift对应项, Dictionary

    do {
        guard let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any] else {return}
        print("json: \(json)")
    
        guard let finalResponse = parseJSON["listofstudents"] as? [String:Any] else {return}
        print("listofstudents::   \(finalResponse)")
    
        guard let nextResponse = finalResponse["nextResponse"] as? [String:Any] else {return}
        print("nextResponse::   \(nextResponse)")
    } catch {
        print(error)
    }
    
        2
  •  1
  •   nathan    9 年前

    nextResponse

    typealias JSON = [String: Any]
    if let finalResponse = parseJSON["listofstudents"] as? JSON {
        let nextResponse = finalResponse ["nextResponse"] as? JSON
        print("nextResponse::   \(nextResponse)")
    }
    
        3
  •  1
  •   Hussain Shabbir    9 年前

    if let finalResponse = parseJSON["listofstudents"] as? [String: Any] {
     //If your finalResponse has list then you can print all the data
      for response in finalResponse {
        let nextResponse = finalResponse ["nextResponse"] as? AnyObject
        print("nextResponse::\(nextResponse)")
      }
    }