从JSON Swift获取数据

时间:2017-12-23 06:28:00

标签: arrays json swift

任何人都可以帮助我吗

解析JSON URL后的数据是

{
    AREA =     (
                {
            "area_name" = "Bhaktamadhu Nagar";
            "city_id" = 4;
            id = 31;
            price = "100.00";
        },
                {
            "area_name" = "Gandamunda";
            "city_id" = 4;
            id = 32;
            price = "100.00";
        }
);
}

还有更多。

我想只获取数组中的area_nameprice

我的代码是那样的

do { 
let parsedData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSDictionary
print(parsedData)}

我在parsedData

中获得了上格式

获取area_nameprice的确切代码是什么,它应该存储在两个单独的数组中aname[]price[]

在发布此内容之前,请不要将其标记为已经搜索过的重复内容。

2 个答案:

答案 0 :(得分:1)

您的JSON数据已转换为[String: AnyObject]

AREA数据为[[String: AnyObject]],因此请创建一个[String: AnyObject]数组。并从数组中获取一个一个值。

How to fetch JSON data from a url using URLSession?

试试这段代码。它的帮助

URLSession.shared.dataTask(with: url) { (data, response, error) in

        if let jsonData = data {
            do {
                let parsedData = try JSONSerialization.jsonObject(with: jsonData, options: .mutableLeaves) as! [String: AnyObject]
                if let area = parsedData["AREA"] as? [[String: AnyObject]] {
                    for a in area {
                        areaNameArr.append(a["area_name"])
                        priceArr.append(a["price"])
                        print(a)

                    }
                }
            }
            catch let error {
                debugPrint(error)
            }
        }
        else {
            debugPrint(error as Any)
        }

    }.resume()

答案 1 :(得分:-1)

使用SwiftyJSON Lib。

简单快捷。

我正在使用它并且以这种方式非常有用:

let session = URLSession(configuration: URLSessionConfiguration.ephemeral)

    self.Task = session.dataTask(with: RequestLink as URLRequest , completionHandler: { (data,response,error) in
        if error != nil {
            print(error as Any)
        }

        let ReadJson4Rest = JSON(data: data!)
        if let Rest_Details = ReadJson4Rest["Result"].array{
            for Details in Rest_Details {

                let Comment  =  Details.dictionaryValue["Comment"]!
                let UserName =  Details.dictionaryValue["User_ID"]!

                if Comment != nil {

                    let FirstChar = UserName.description.characters.first
                    self.GetUserImage(UserName: UserName.string! ,AlphabetCat: (FirstChar?.description)!)
                    DispatchQueue.main.async {
                        self.CommentValue.append(Comment.string!)
                        self.UserNames.append(UserName.string!)
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Load"), object: nil)
                    }
                }
            }
        }
    })
    self.Task?.resume() 
}