I am having issue fetching products "name" from a json file.
and here is my code so far. and it prints complete json. I just want to fetch name of the products from this file.
guard let url = URL(string: "https://URL/get_products.php") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse, options: [])
print(jsonResponse)
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
The structure is pretty clear, values next to string keys are dictionaries, next to ordinal numbers are arrays:
if let jsonResponse = try JSONSerialization.jsonObject(with: dataResponse) as? [String:Any],
let data = jsonResponse["data"] as? [[String:Any]] {
for anItem in data {
if let products = anItem["products"] as? [[String:Any]] {
for product in products {
if let name = product["name"] as? String {
print(name)
}
}
}
}
}
A better way is to parse the JSON into structs with JSONDecoder
Related
I'm trying to make an async API get request to openweathermap.org 's API. The result should be this JSON structure. I'm particularly trying to get the temperature. I was taught to work with it by wrapping the JSON to a dictionary. Thing is I don't know what I can use to specify the object "main" (in the JSON) and get the temperature. Do I have to iterate object by object? This is my code so far (side note: is it worrying that my app uses 50 mb of RAM?)
let url = URL(string: stringURL)
let myQ = DispatchQueue.init(label: "getCityDetails")
myQ.async {
let session = URLSession.shared
let m = session.dataTask(with: url!, completionHandler: {(data, response, error) in
if let error = error {
print(error.localizedDescription)
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Error with the response, unexpected status code: \(String(describing: response))")
return
}
do {
if let d = data{
let dictionaryObj = try JSONSerialization.jsonObject(with: d, options: []) as! NSDictionary
print(dictionaryObj)
}
}catch{
print(error.localizedDescription)
}
})
m.resume()
The first point is that the default URLSession works in a background thread so you dont need to create a dispatch queue (alos you are not using it correctly). The second point tries to use optional data not to use try/catch. Finally you could try to use Swift 5 together to the protocol Codable to have better code, simple and secure.
let url = URL(string: "https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02")!
URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) in
if let error = error {
print(error.localizedDescription)
return
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Error with the response, unexpected status code: \(String(describing: response))")
return
}
guard let data = data else {
return
}
guard let dictionaryObj = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
return
}
if let main = dictionaryObj["main"] as? [String: Any], let temperature = main["temp"] {
DispatchQueue.main.async {
print("Temperature: \(temperature)")
}
}
}).resume()
This is my JSON array
[
{
"dollar":"15000",
"date":"1397-12-12"
}
]
i want to show dollar and date values in two different label but i have this type mismatch error :
typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
this is my Struct :
struct Dollar_Date : Codable {
let dollar : String
let date : String
}
and this is my code in view controller :
func dollarLabel() {
let urlString = DOLLAR_DATE_BASE_URL
guard let url = URL(string: urlString) else { return }
// 2
URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!.localizedDescription)
}
guard let data = data else { return }
do {
// 3
//Decode data
let JSONData = try JSONDecoder().decode(Dollar_Date.self, from: data)
// 4
print(JSONData.dollar)
//Get back to the main queue
DispatchQueue.main.async {
self.main_Price.text = JSONData.dollar
self.data_Label.text = JSONData.date
}
} catch let jsonError {
print(jsonError)
}
// 5
}.resume()
}
Try this:
guard let jsonArray = JSONData as? [[String: Any]] else {
return
}
print(jsonArray)
//Now get title value
guard let title = jsonArray[0]["title"] as? String else { return } print(title)
You get an error because your data contains an array of JSON (dictionary as well), not JSON itself.
So you can't decode with
let JSONData = try JSONDecoder().decode(Dollar_Date.self, from: data)
But you have to do it manually:
EDIT:
guard let json = data as? [[String:Any]] else{return}
Now you can retrieve dollars and date from all the elements of your array:
// These are because you have to access an element of the array
guard let dollar = json[0]["dollar"] as? String else {return}
guard let date = json[0]["date"] as? String else {return}
DispatchQueue.main.async {
self.main_Price.text = dollar
self.data_Label.text = date
}
if your data can contain multiple value (dollars-date couples) you have to loop your array. By the previous example, you should do:
for element in json{
guard let dollar = element["dollar"] as? String else {return}
guard let date = element["date"] as? String else {return}
// do some stuff with each value
}
I have been struggling all week. I am new to programming. I cannot turn a simple JSON file into a dictionary in Xcode. There is little simplified documentation online using the new method of Codable. So I am using a walkthrough, which has the following code.
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
guard let path = Bundle.main.path(forResource: "menu", ofType: "json") else { return }
let url = URL(fileURLWithPath: path)
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
//print(json)
guard let array = json as? [Any] else { return }
for user in array {
guard let userDict = user as? [String: Any] else { return }
guard let drinks = userDict["drinks"] as? String else { print("not a String"); return }
guard let junkFood = userDict["junk-food"] as? String else { return }
print(drinks)
print(junkFood)
print(" ")
}
}
catch {
print(error)
}
}
}
The below code is what my JSON looks like.
{"menu": {
"drinks": [
{"coke": "20"},
{"pepsi": "20"},
{"water": "20"}
],
"junk-food": [
{"hamburger": "40"},
{"fries": "20"},
{"pizza": "20"}
]
}}
Can anyone please walk me through, or show me some simplified documentation as to how I can turn the JSON into a dictionary that I can later map the data from? I am using Xcode and trying to work out Swift 4.
Thanks in advance for your patience.
My guess is that your json is actually a Dictionary not an Array. So guard let array = json as? [Any] else { return } is falling through because the json is [String: Any]. You can get to the array with the "menu" key.
Here's an updated version of your code:
do {
let data = try Data(contentsOf: url)
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers)
//print(json)
guard let menuDict = json as? [String: Any] else { return }
guard let drinks = menuDict["drinks"] as? [[String: Any]] else {
print("not an array of dictionaries")
return
}
guard let junkFood = menuDict["junk-food"] as? [[String: Any]] else {
print("not an array of dictionaries")
return
}
print(drinks)
print(junkFood)
print(" ")
}
Try that, let me know if it works. This is just the do block by the way.
I am pulling down a json stream? From a phant server I can pull the data down parse it and print it in xcode. I need to pull out specific values but the json does not have a title and I can not seem to figure it out.
My JSON Data
(
{
lat = "36.123450";
long = "-97.123459";
timestamp = "2017-04-26T05:55:15.106Z";
},
My Current Code in Swift
let url = URL(string: "https://data.sparkfun.com/output/5JDdvbVgx6urREAVgKOM.json")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error != nil {
print("error")
} else {
if let content = data {
do {
// JSONArray
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
let Coordinates = myJson["lat"] as! [[String:Any]]
print(Coordinates)
} catch {
}
}
}
}
task.resume()
}
Please read the JSON. [] represents an array, {} a dictionary.
The JSON is an array of dictionaries. All keys and values are String.
let url = URL(string: "https://data.sparkfun.com/output/5JDdvbVgx6urREAVgKOM.json")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
if error != nil {
print("error: ", error!)
} else {
do {
let coordinateArray = try JSONSerialization.jsonObject(with: data!) as! [[String:String]]
for coodinate in coordinateArray {
let lat = coodinate["lat"] ?? "n/a"
let long = coodinate["long"] ?? "n/a"
let timestamp = coodinate["timestamp"] ?? "n/a"
print("latitude: \(lat), longitude: \(long), timestamp: \(timestamp)")
}
} catch {
print (error)
}
}
}
task.resume()
As always, .mutableContainers has no effect in Swift but the tutorials which suggests that will never die off.
It looks like your JSON data is an array of objects, so myJson will be an array of dictionaries.
I would try something like this:
if let myJson = try JSONSerialization.jsonObject(with: content, options: []) as? [AnyObject] {
print(myJson)
for obj in myJson {
if let dict = obj as? [String:AnyObject] {
print(dict)
if let lat = dict["lat"] as? String,
let lng = dict["long"] as? String,
let time = dict["timestamp"] as? String {
// do something with stuff
}
}
}
}
Is it possible that someone could show me how to get the names of these pizza places printing out? My application prints out the expected "Status Code: 200". However, my console only shows empty brackets []. I suspect that I am not pulling values from my JSON object properly.
I'm using this link for my API.
Link For API
Question
How can I properly fetch values from my serialized JSON object?
relevant code:
// Response
if let httpResponse = response as? NSHTTPURLResponse where httpResponse.statusCode == 200, let data = data {
print("Status Code: \(httpResponse.statusCode)")
do {
let json = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
if let pizzaPlaces = json["response"] as? [[String: AnyObject]] {
for place in pizzaPlaces {
if let name = place ["name"] as? String {
self.PizzaClass.append(name)
}
}
}
} catch {
print("Error Serializing JSON Data: \(error)")
}
print(self.PizzaClass)
}
}).resume()
You need to cast your NSJSONSerialization.JSONObjectWithData result as a [String:AnyObject].
let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]
Once you have that all you need to do is pay attention to what you're casting. Take the code below for an example. If we want to get our response object using jsonObject["response"] what kind of data structure do we have?
"response": {
"venues": [{
//... continues
}]
}
On the left we have "response" which is a string, on the right we have {} which is an AnyObject. So we have [String: AnyObject]. You just need to think about what object your dealing with piece by piece. Below is a working example that you can just paste into your application.
full working code:
func getJson() {
let request = NSMutableURLRequest(URL: NSURL(string: "https://api.foursquare.com/v2/venues/search?client_id=0F5M0EYOOFYLBXUOKTFKL5JBRZQHAQF4HEM1AG5FDX5ABRME&client_secret=FCEG5DWOASDDYII4U3AAO4DQL2O3TCN3NRZBKK01GFMVB21G&v=20130815%20&ll=29.5961,-104.2243&query=burritos")!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = session.dataTaskWithRequest(request) { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
guard let testResponse = response as? NSHTTPURLResponse else {
print("\(response)")
return
}
guard let status = HTTPStatusCodes(rawValue: testResponse.statusCode) else {
print("failed to unwrap status")
return
}
print(status)
switch status {
case .Created:
print("ehem")
case .BadRequest:
print("bad request")
case .Ok:
print("ok")
guard let returnedData = data else {
print("no data was returned")
break
}
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(returnedData, options: .MutableLeaves) as! [String: AnyObject]
guard let response = jsonObject["response"] as? [String: AnyObject] else { return }
guard let venues = response["venues"] as? [AnyObject] else { return }
guard let location = venues[0]["location"] as? [String:AnyObject] else { return }
guard let formattedAddress = location["formattedAddress"] else { return }
print("response: \n\n \(response)\n------")
print("venues : \n\n \(venues)\n-------")
print("location : \n\n \(location)\n------")
print("formatted address : \n \(formattedAddress)")
} catch let error {
print(error)
}
// update user interface
dispatch_sync(dispatch_get_main_queue()) {
print("update your interface on the main thread")
}
}
}
task.resume()
}
place this either in its own file our outside of the class declaration,
enum HTTPStatusCodes : Int {
case Created = 202
case Ok = 200
case BadRequest = 404
}
Not that this was what you are looking for, but since you are new to Swift take a look at Alamofire. It handles JSON serialization for you. And when you need to chain calls PromiseKit is super slick.
Alamofire.request(.GET, url).responseJSON {response in
switch (response.result) {
case .Success(let value):
let pizzas = JSON(value).arrayValue
for place in pizzaPlaces {
if let name = place ["name"] as? String {
self.PizzaClass.append(name)
}
}
case .Failure(let error):
if let data = response.data, let dataString = String(data: data, encoding: NSUTF8StringEncoding) {
print("ERROR data: \(dataString)")
}
print("ERROR: \(error)")
}
}