parse string and send as Json in swift - ios

I have real big problem finding the right code which helps me to parse String to JSON and then send to external server. I'm using xCode 6.1, so some ways of parsing won't work for me, like SwiftyJSON.
On internet i only can find the way to send String , but not JSON, or if i found something it won't work.
I'm beginner in iOS and it would really help me if someone can explain me how to do it.
Thank you a lot.

If you have JSON String convert to NSData object.Check the data object before sending to an external server if data is valid JSON format or not by using NSJSONSerialization.I am giving sample code to how can check JSON Data valid or not.
suppose you String is like this,
let jsonString = "{\"device\":\"iPhone 6\",\"OS\":\"iOS 9\",\"name\":\"Apple\"}"
let data = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
do {
let responseData = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if responseData != nil { // valid JSON
//Now pass data object to server
}
} catch {
NSLog("ERROR when parse JSON")
}

Related

JSONSerialization did't serialised data as server send

JSONSerialization didn't serialise data as server send. It reverses turn the data. I use data filter API from backend. its send the accurate data, I've also checked in postman and android side but iOS code changes the response.
do {
if let json = try JSONSerialization.jsonObject(with: usableData, options: .mutableLeaves) as? [String: Any] {
}
} catch let error {
OperationQueue.main.addOperation() {
SVProgressHUD.dismiss()
}
}
But if i convert the data into string then its shows correct. WHY?
var jsonString : String?
jsonString = String.init(data: data, encoding: String.Encoding.utf8)
Finally, I've got the solution. Server sends the data more than 100 keys in dictionary which is incorrect form, with this format our json serialisation could not able to serialised the data as we got from server.so we have decided to change the structure from dictionary to Array.
Incorrect form
1025{
id:1025
name:xyz
area:23123
}
1026{
id:1026
name:xyz
area:23123
}
1027{
id:1027
name:xyz
area:23123
}
Correct Form
[
id:1025
name:xyz
area:23123
,
id:1026
name:xyz
area:23123
,
id:1027
name:xyz
area:23123
]

use of "po" to get data from server response in console log

i know this is very basic question that i am gonna ask but i need to ask how can i access data which is dictionary that is getting from server.
here is my response
JSON: {
message = "The email must be a valid email address.";}
now i want to do "po" in console log so what to write after in po statement
Thanks
All you need type
po yourResponseAsDictionary["message"]
UPDATED
Sorry I was thinking you already converted it.
If you are not using anything like SwiftyJSON or ObjectMapper to parse your json data then you can do just the following.
But I would recommend to use some lib to convert response directly to your model
let yourResponseFromNetwork = "{ \"country_code\" : \"+9\", \"user_id\" : 123456}"
if let data = yourResponseFromNetwork.data(using: String.Encoding.utf8) {
do {
if let dic = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:Any] {
let countryCode = dic["country_code"]
let userId = dic["user_id"]
}
} catch {
print("Error occurred")
}
}

Dealing with DataResponse<Any> in Xcode 8 (Swift)

I am a newbie to iOS and I am using alamofire. When i call the API the result is successfully getting printed to console as shown
What I want is, to only extract the message from this response and present it to user. How to do it?
I have searched for this but I found content related to converting string to JSON object or JSON object to JSON string. But my response is of type DataResponse<Any> and I don't know exactly how to deal with it.
P.s I am using Xcode 8, Swift 3.
You can try something like this:
if let object = response.result.value as? [String:Any], let message = object["message"] as? String {
print(message) // "User has been successfully registrered"
}
As Rashwan L Answer is perfect !!
Still I am suggesting A better way to do it using ObjectMapper
It is very easy to access each property easily
First You need to Download SwiftyJSONAccelerator application in your system which let you convert your JSON Response to Class or struct whatever you need.
From
https://github.com/insanoid/SwiftyJSONAccelerator
And Create Class for your JSON, And Select ObjectMapper if you are not using SwiftyJosn from drop down Where there are three options.
Drag and drop all generated class file to your XCode make sure you select Copy Item if needed Check box Selected
How to use ?
import ObjectMapper
WebServices().getMyWSResponse(success: { (response) in
guard let res = response as? [String:Any], let obect = Mapper<MYGeneratedModelClass>().map(JSON: res) else {
return
}
//Here you get obect , You can access object.message
}, error: { (error) in
})
}
Note: WebServices().getMyWSResponse is My Class to call ws you don't need to worry about that
Hope it is helpful to you

SwiftyJSON to read local file

So my app is using a JSON API response to read some data from server. Since the API is not yet ready i want to use a sample JSON file which is stored in my app itself. Since all my code uses SwiftyJSON i want to stick to it for the local file.
I am doing the following in my ViewDidLoad method and somehow this end result is a blank array. Do you know what should i change in this code to make it work?
//Direct JSON
if let path = NSBundle.mainBundle().pathForResource("XXYYXZZfile", ofType: "json")
{
do{
let pathAsData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
let json = JSON(pathAsData)
print(json)
} catch{
print("Some error")
}
}
When using SwiftyJSON with NSData you have to specify the "data:" parameter for the JSON initializer:
let json = JSON(data: pathAsData)
otherwise it tries to use other available initializers and will fail with an error or even, like in your case, will fail silently with a misinterpreted input and wrong output.

Alamofire Get Request and JSON Response

I'm trying to use the Yoda API and send a request using the Alamofire Swift framework. I know that the API is correctly working, as I have tested the endpoint with my Mashape API key multiple times. I can also see that the requests are being sent (homepage of Mashape under my application). However my JSON response is always nil.
func handleRequest(words:String){
var saying = words.stringByReplacingOccurrencesOfString(" ", withString: "+");
saying = "?sentence=" + saying;
let url = NSURL(string: (baseURL+saying));
println(url);
var response:String;
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = additionalHeaders;
Alamofire.request(.GET, url!).responseJSON { (_, _, JSON, _) in
println(JSON);
}
}
The words string can be "This is my first sentence" and it will automatically replace the spaces with "+" as per the API spec. Please Ignore the multiple println statements, they are just for debugging.
This is just proof of concept code, its purposely not doing much error checking and isn't pretty for that reason. If you have any suggestions I would appreciate them.
For some reason it's an issue I've too with the Alamofire request for JSON. It is the way I handle the JSON requests using Alamofire :
Alamofire.request(.GET, urlTo, parameters: nil, encoding: .URL).responseString(completionHandler: {
(request: NSURLRequest, response: NSHTTPURLResponse?, responseBody: String?, error: NSError?) -> Void in
// Convert the response to NSData to handle with SwiftyJSON
if let data = (responseBody as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
let json = JSON(data: data)
println(json)
}
})
I strongly recommend you using SwiftyJSON to manage the JSON in a better and easy way, it's up to you.
I hope this help you.
Alamofire request have several method for handle response. Try to handle data response and convert it to String. Confirm that response JSON is normal.
Alamofire.request(.GET, url!).response { (_, _, data, error) in
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println(str)
println(error)
}
Also checkout error while parsing JSON data.

Resources