Get data from array in response in Swift - json

i'm hitting an API and response is shown like this,
"responseBody": {
"data": [
"{\"AED_USD\":0.272255,\"USD_AED\":3.67305}"
]
}
I'm confuse that how i can take out value of AED_USD and USD_AED from this array data. I have try to take all of the response in array and try to get value from index base but isn't working. How i can get the value? My code is this,
let params = ["sourceCurrency":self.accountFromTxt.text!,
"targetCurrency":self.accountToTxt.text!] as [String : AnyObject]
print(params)
APIService.ExchangePrice(showActivityIndicator: true, parameters: params) { (responseObject) in
if (responseObject?.status)!
{
self.print(responseObject?.data)
self.exchangeRateArray.removeAll()
if let usersDataArray = responseObject?.data as? [[String : Any]] {
for userData in usersDataArray {
self.exchangeRateArray.append(ExchangeRateCurrency(JSON:userData)!)
}
if usersDataArray.count == 0
{
//Empty Message
self.view.showEmptyScreenMessage(text: EmptyScreenMessages.transactionDetailMessage)
}
self.print(self.exchangeRateArray.count,self.exchangeRateArray[0])
}
}
else
{
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}

Your data is in string form, change string to JSON NSdictonary.
try to convert like this
let str = "{\"AED_USD\":0.272257,\"USD_AED\":3.673001}"
if let data = str.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
// In your code.
let params = ["sourceCurrency":self.accountFromTxt.text!,
"targetCurrency":self.accountToTxt.text!] as [String : AnyObject]
print(params)
APIService.ExchangePrice(showActivityIndicator: true, parameters: params) { (responseObject) in
if (responseObject?.status)!
{
self.print(responseObject?.data)
self.exchangeRateArray.removeAll()
if let usersDataArray = responseObject?.data as? [[String : Any]] {
for userData in usersDataArray {
print(userData)
// if you get string from userData
if let data = userData.data(using: String.Encoding.utf8) {
do {
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any]
print(json)
} catch {
print("Something went wrong")
}
}
}
if usersDataArray.count == 0
{
//Empty Message
self.view.showEmptyScreenMessage(text: EmptyScreenMessages.transactionDetailMessage)
}
//self.print(self.exchangeRateArray.count,self.exchangeRateArray[0])
}
}
else
{
Utilities.showBar(text: responseObject?.errorObject?.message)
}
}

Related

How to convert Raw dictionary to JSON string?

I have this type of dictionary:
{
“event”: {
“type”: “message_create”, “message_create”: {
“target”: {
“recipient_id”: “RECIPIENT_USER_ID”
}, “message_data”: {
“text”: “Hello World!”,
}
}
}
I want to convert this dictionary into JSON string format, but not able to do it. Please anyone guide me on this.
This is the code till I am trying after sending message I am getting bad authenticating data message from server -
func sendMessage(_ userInfo: String) {
let requestURL = URL(string: "https://api.twitter.com/1.1/direct_messages/events/new.json")
Alamofire.request(requestURL!, method: .post,
encoding: URLEncoding.default,
headers: getRequestHeader()).responseJSON { (response) in
print(response)
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print("FAILURE ERROR : \(error.localizedDescription)")
print("ERROR : \(error)")
if let data = response.data {
print("Print Server Error: " + String(data: data, encoding: String.Encoding.utf8)!)
}
}
}
}
// MARK: - Get Request Header
func getRequestHeader() -> ([String: String]) {
return ["authorization": "","CONSUMER_KEY":"",
"CONSUMER_SECRET":"",
"oauth_secret":"7W2Gx4KEjz7d164NPvJaOktzhaSPpV3VNjvyjpIqaDc02",
"oauth_token":"2605063830-IffuOmn2tEajFXY6khbzmeMwNoUvGkQ8qrYonzw",
"oauth_version":"1.0",
"oauth_signature_method":"HMAC-SHA1",
"Content-Type": "application/json"
]
}
For the purpose of focusing on getting the json string (without caring about how you got the dictionary), I would assume that your myDict is the dictionary that you want to convert to json string:
let json = """
{
"event": {
"type": "message_create", "message_create": {
"target": {
"recipient_id": "RECIPIENT_USER_ID"
},
"message_data": {
"text": "Hello World!"
}
}
}
}
""".data(using: .utf8)
var myDict: [String: Any] = [: ]
do {
if let dict = try JSONSerialization.jsonObject(with: json!, options: []) as? [String: Any] {
myDict = dict
}
} catch {
print(error)
}
So now we want to convert myDict as a json string:
do {
// converting `myDict` to Json Data, and then
// getting our json as string from the `jsonData`:
if let jsonData = try JSONSerialization.data(withJSONObject: myDict, options: []) as? Data,
let jsonString = String(data: jsonData, encoding: .utf8) {
print(jsonString)
}
} catch {
print(error)
}
jsonString is now what are you looking for! you should see on the log:
{"event":{"type":"message_create","message_create":{"target":{"recipient_id":"RECIPIENT_USER_ID"},"message_data":{"text":"Hello
World!"}}}}
which is perfectly valid json.
public extension NSDictionary{
public func toJSONString() -> String{
if JSONSerialization.isValidJSONObject(self) {
do{
let data = try JSONSerialization.data(withJSONObject: self, options: JSONSerialization.WritingOptions(rawValue: 0))
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch {
print("error")
}
}
return ""
}
}

Swift: how to parse json to a dictionary

I have the following as a json output in console
{
cash_machine = "0.08924368023872375488";
dishwasher = "0.06437973678112030029";
modem = "0.04461396858096122742";
monitor = "0.28455805778503417969";
nematode = "0.04982925951480865479";
screen = "0.05664909631013870239";
television = "0.03846205398440361023";
}
My code is
let session = URLSession.shared.dataTask(with: r) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
// experiment here
// if statement ends here
} .resume()
I was wondering how I'd parse this into a dictionary: {"key1" : "value1", "key2" : "value2", "key3" : "value3", ..., "key_n", "value_n"}
Try something along these lines
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String]
for key in json.keys {
print("\(key) : \(json[key])")
}
}

Not getting expected results parsing JSON in Swift

I have a web service that look like this
[
{
"id_test" : "1",
"title":"test1"
},
{
"id_test" : "2",
"title":"test2"
},{
"id_test" : "3",
"title":"test3"
},
]
I use this code to read the json in my program:
func downloadJsonWithUrl()
{
let url = URL(string:"weserviceurl")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil
{
print("Error")
}
else
{
if let content = data
{
do
{
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(myJson)
}
catch
{
}
}
}
}
task.resume()
}
My question is, at the moment to use use this code below my serialization:
if let info = myJson as? NSArray
{
if let categories = info["title"]
{
print(categories)
}
}
does not work. It returns empty. Why?
Try this
func downloadJsonWithUrl() {
let url = URL(string:"link")
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error != nil {
print("Error")
} else {
if let content = data {
do {
let myJson = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as! [AnyObject]
var categories: [String] = []
for item in myJson {
categories.append(item["title"] as! String)
}
print(categories)
} catch {
print(error)
}
}
}
}
task.resume()
}
You should use swift Array and Dictionary types. For example, ... as? [[String: Any]] says that you're expecting an array of dictionaries:
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
guard let data = data, error == nil else {
print("\(error)")
return
}
guard let json = try? JSONSerialization.jsonObject(with: data), let array = json as? [[String: Any]] else {
print("not JSON array of dictionaries")
return
}
for dictionary in array {
if let idTest = dictionary["id_test"], let title = dictionary["title"] {
print("\(idTest): \(title)")
}
}
}

how to read data from json in swift2

I am trying to read email from a json file in swift(2.2) which is:
{ "employees" : [
{
"name": "sudhanshu",
"email": "sudhanshu.bharti#digitalavenues.com",
"password": "password"
"profilePic": ""
},
{
"name": "prokriti",
"email": "prokriti.roy#digitalavenues.com",
"password": "password#123",
"profilePic": ""
}
]}
But i am getting error " Error Domain=NSCocoaErrorDomain Code=3840 "Unescaped control character around character 128." UserInfo={NSDebugDescription=Unescaped control character around character 128.}" i have seen earlier posts but unable to find where exactly problem is??
if let path = NSBundle.mainBundle().pathForResource("Employees", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
do {
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let error = jsonResult["error"] {
print("Error is: \(error)")
} else {
if let person = jsonResult["email"] {
print(person) // dictionary[#"quotables"]
}
}
} catch let error as NSError {
print("Error is: \(error)")
}
}
}
Thanks in advance!
"password": "password”
should be
"password": "password"
You have an invalid ” character instead of a ".
Update
Now that you've fixed your invalid character, you can access your data. But you're trying to cast as an NSDictionary something that's actually an array, if I believe the JSON excerpt you showed us.
So you should do something like this instead in your do:
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [[String: String]] {
for jsonDictionary in jsonResult {
if let person = jsonDictionary["email"] {
print(person)
}
}
}
Update and fix
if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject] {
if let employees = jsonResult["Employees"] as? [[String:String]] {
for employee in employees {
if let person = employee["email"] {
print(person)
}
}
}
}
You are trying to access directly email key from the dictionary. while you need to first access array from the key "employees" & then you need to get value from "email" key.
if let path = NSBundle.mainBundle().pathForResource("Employees", ofType: "json") {
if let data = NSData(contentsOfFile: path) {
do {
let jsonResult: NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
if let error = jsonResult["error"] {
print("Error is: \(error)")
} else {
let person = jsonResult["employees"] as! NSArray
for i in 0..<person.count
{
let dict = person.objectAtIndex(i) as! NSDictionary
let strEmail = dict["email"] as! String
print(strEmail)
}
}
} catch let error as NSError {
print("Error is: \(error)")
}
}

How do I get values from a complex JSON object?

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)")
}
}