Issue with JSON and Swift - \u00c3\u00a9 é instead of é - json

I am trying to display some JSON data on my iOS app but I am having an issue with displaying it correctly using Swift.
When I use the normal JSONSerializer for \u00c3\u00a9 i get é but I want to display é. I don't understand if it is an issue with say using UTF-16 rather than UTF-8 or something else?
Does anyone have any suggestions how I would convert \u00c3\u00a9 straight to é in Swift, from a JSON received from an API.

Not sure which encoding you're using, but this code works for both .utf8 and .utf16:
let jsonString = "{\"foo\": \"áéíóú\"}"
let data = jsonString.data(using: .utf16)!
do {
let object = try JSONSerialization.jsonObject(with: data, options: [])
if let dict = object as? [AnyHashable: Any], let text = dict["foo"] as? String {
print("Extracted text: \(text)")
}
}
catch let e {
// TODO: Handle error
print("Error processing JSON: \(e)")
}

was the same problem. Necessary use this code, it works:
Alamofire.request(url, method: .get, parameters: params)
.responseJSON{ response in
guard let data = response.data else {return}
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
let json = jsonResult["response_goods"] as! [[String:String]]
print(json) } catch let err as NSError {print(err)
}
}

Related

Swift MacOS getting bad json response from jsonSerialization

I am trying to convert a string to JSON in Swift.
Here's the string, which I am getting by pulling the innerHTML from a WKWebView.
{"list":{"pagination":{"count":3,"hasMoreItems":false,"totalItems":3,"skipCount":0,"maxItems":100},"entries":[{"entry":{"createdAt":"2020-06-16T21:00:32.714+0000","isFolder":false,"isFile":true,"createdByUser":{"id":"UserFName.userLName#xxxxxxxx.com","displayName":"UserFName userLName"},"modifiedAt":"2020-06-16T21:00:32.714+0000","modifiedByUser":{"id":"UserFName.userLName#xxxxxxxx.com","displayName":"UserFName userLName"},"naxxxxxxxxme":"00-invest-2020-06-16-17-00-32-716.txt","id":"028b4c82-09b8-4ee5-b4fa-9696a33b026d","nodeType":"log:fileNode","content":{"mimeType":"text/plain","mimeTypeName":"Plain Text","sizeInBytes":609373,"encoding":"UTF-8"},"parentId":"ba647bfc-a889-4d91-9211-4220cfe7d90a"}},{"entry":{"createdAt":"2020-06-16T21:01:12.828+0000","isFolder":false,"isFile":true,"createdByUser":{"id":"UserFName.userLName#xxxxxxxx.com","displayName":"UserFName userLName"},"modifiedAt":"2020-06-16T21:01:12.828+0000","modifiedByUser":{"id":"UserFName.userLName#xxxxxxxx.com","displayName":"UserFName userLName"},"name":"00-monetize-2020-06-16-17-01-12-830.txt","id":"d6412e3a-fea5-4d4d-a962-d91cde294bc9","nodeType":"log:fileNode","content":{"mimeType":"text/plain","mimeTypeName":"Plain Text","sizeInBytes":996653,"encoding":"UTF-8"},"parentId":"ba647bfc-a889-4d91-9211-4220cfe7d90a"}},{"entry":{"createdAt":"2020-06-16T18:33:49.344+0000","isFolder":true,"isFile":false,"createdByUser":{"id":"UserFName.userLName#xxxxxxxx.com","displayName":"UserFName userLName"},"modifiedAt":"2020-06-16T18:34:49.211+0000","modifiedByUser":{"id":"UserFName.userLName#xxxxxxxx.com","displayName":"UserFName userLName"},"name":"20200616","id":"d881db96-ddcb-44ae-99e1-ffe3ac0c2810","nodeType":"cm:folder","parentId":"2fcf4c49-be4c-4f2c-a90b-654ae092c63e"}}]}}
I've checked the string in JSON Lint and it says it is valid.
Here's what I am doing in my code to convert it:
let strJSONLiteral = """
\(strJSON)
"""
//convert string to json
let data = strJSONLiteral.data(using: .utf8)!
do {
if let myJSON = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
{
print(myJSON) // use the json here
} else {
print("bad json")
}
} catch let error as NSError {
print(error.localizedDescription)
}
The error is occurring in the JSONSerialization attempt. I'm getting nil for myJSON. Data check looked ok, has 1600+ bytes.
The top-level JSON is of type Dictionary while you're trying to decode an Array of Dictionary. To fix this
Replace:
if let myJSON = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [Dictionary<String,Any>]
With:
if let myJSON = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? Dictionary<String,Any>
Or you can just use [String: Any].
Add-on: You should probably do a bit of research on Codable and try to use it for these scenarios.

Convert string preceeded with 0 to Json in Swift 4

I'm trying to encode an integer that starts with a 0 into JSON using swift 4.
I'm using a pretty standard JSONSerialization library, but for some reason, after converting the string to data using utf8, I cannot serialize it.
let code = "012345" // example code
let body = "{\"code\": " + code + "}"
let stringData = body.data(using: .utf8)!
let jsonArray = try? JSONSerialization.jsonObject(with: stringData, options : .allowFragments) [returns nil]
let data: Data? = try? JSONSerialization.data(withJSONObject: jsonArray as Any, options: .prettyPrinted)
Currently, the code breaks on the second to last line (starting with let jsonArray) and returns nil. Note that if I were to change code to "112345", there would be no error. Any help is appreciated, thanks!
Instead of manually creating string, use Dictionary and JSONSerialization to create data as below,
let code = "012345"
let body: [String: Any] = ["code": code]
do {
let stringData = try JSONSerialization.data(withJSONObject: body, options: .sortedKeys)
print(String.init(data: stringData, encoding: .utf8)!)
} catch {
print(error)
}
Output
{"code":"012345"}

JSON String to Dictionary in Swift 4

I'm getting response from server in JSON in this format.
{"ResponseCode":1,"StudentDetails":[{"Student_ID":1,"Student_SchoolID":1,"Student_BranchID":1,"Student_ClassID":1,"Student_FirstName":"1","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"19/03/2017","Student_EnrollmentNo":"1","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/IMG100710620180809104233860.JPG","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":278324,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Ganu now","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":267971,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":4894,"Student_FirstName":"Poonam Dillo saii","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"2211","Class_Name":"Nursery A","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/FB_IMG_145451330612110622062018203844.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":272466,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Poonam ganu","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":273560,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14564,"Student_FirstName":"Ganesh kumar saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"Primary","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":133262,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":5065,"Student_FirstName":"Lavish saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"04/02/2018","Student_EnrollmentNo":"09EEBMIT29","Class_Name":"KG ICA","Student_Password":"123456","Student_PrimaryEmailID":"ganeshsaini01#gmail.com","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/download110682201811024710015409877121411061541069294120.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}],"StudentMenusCount":[{"CountValue":0,"StudentId":0,"CountFor":"StudyPlanner","DatabaseID":0,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}]}
Now this I'm getting in JSON String format. I need to convert it to Dictionary. I'm using this code to parse json.
let myJson = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as Any
if myJson is String {
print(myJson) // Printing Here as myJson is String.
}
If I'm writing in above code as:
let myJson = try JSONSerialization.jsonObject(with: response.data!, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]
It's complaining about bad json than. Any idea of how to convert json string to Dictionary here?
This is the way to do it but you should say what is the error:
if let data = Data(result.utf8) {
do {
let myJson = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: Any]
} catch let error {
print(error)
}
}
I think the JSON is fine, however the way you parse JSON is not.
I tried with this code and the result is expected.
let response = """
{"ResponseCode":1,"StudentDetails":[{"Student_ID":1,"Student_SchoolID":1,"Student_BranchID":1,"Student_ClassID":1,"Student_FirstName":"1","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"19/03/2017","Student_EnrollmentNo":"1","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/IMG100710620180809104233860.JPG","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":278324,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Ganu now","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":267971,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":4894,"Student_FirstName":"Poonam Dillo saii","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"2211","Class_Name":"Nursery A","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/FB_IMG_145451330612110622062018203844.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":272466,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14193,"Student_FirstName":"Poonam ganu","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"1 QA","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":273560,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":14564,"Student_FirstName":"Ganesh kumar saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"01/01/0001","Student_EnrollmentNo":"","Class_Name":"Primary","Student_Password":"123456","Student_PrimaryEmailID":"","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":false,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0},{"Student_ID":133262,"Student_SchoolID":1404,"Student_BranchID":1408,"Student_ClassID":5065,"Student_FirstName":"Lavish saini","Student_MiddleName":"","Student_LastName":"","Student_Gender":"Male","Student_DOB":"04/02/2018","Student_EnrollmentNo":"09EEBMIT29","Class_Name":"KG ICA","Student_Password":"123456","Student_PrimaryEmailID":"ganeshsaini01#gmail.com","SchoolLogo":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/branch/compress/images106472017105803.jpg","Student_IsProfileImageUpload":true,"Student_IsSoftDelete":false,"Student_IsActive":true,"Branch_Name":"1","ProfilePicture":"https://s3-us-west-2.amazonaws.com/1/uploadeddocs/student/compress/download110682201811024710015409877121411061541069294120.jpg","DatabaseID":106,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}],"StudentMenusCount":[{"CountValue":0,"StudentId":0,"CountFor":"StudyPlanner","DatabaseID":0,"IsSMSDisabled":false,"SMSBalance":null,"SMSSettingID":0,"NotificationSettingID":0,"IsSuperAdminUser":false,"SelectedSessionMasterID":0,"TargetedDate":null,"SelectedSessionType":0}]}
"""
if let data = response.data(using: .utf8) {
let myJson = try JSONSerialization.jsonObject(with: data,
options: JSONSerialization.ReadingOptions.allowFragments) as Any
if myJson is String {
print(myJson) // <-- This will not print anything as myJson is not a string
}
if let dict = myJson as? [String: Any] {
print(dict.keys) // <-- This will print a list of keys
}
}

iOS Swift:"JSON text did not start with array or object and option to allow fragments not set."

When I converting Json string to dictionary in swift I got the Issue:Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I don't know to fix the issue please give idea for fix the issue.Here I gave my code what i am tried..
The method for converting Json string to dictionary is,
func convertToDictionary(from text: String) throws -> [String: String] {
guard let data = text.data(using: .utf8) else { return [:] }
let anyResult: Any = try JSONSerialization.jsonObject(with: data, options: [])
return anyResult as? [String: String] ?? [:]
}
The Json String is: "[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]"
And the Usage of method was:
let jsonString = NSString(data: responseObject as! Data, encoding: String.Encoding.utf8.rawValue)!
print(jsonString)
do {
let dictionary:NSDictionary = try self.convertToDictionary(from: jsonString as String) as NSDictionary
print(dictionary)
} catch {
print(error)
}
Read the error gentleman. Error is 'allow fragments not set'.
Just Just just set .allowFragments.
That's it. (Make sure response is not malformatted)
JSONSerialization.jsonObject(with: data!, options: .allowFragments)
You can try this:
let str = "[{\"propertyId\":\"1\",\"inspectionTemplateId\":1118,\"value\":[{\"widgetControllerId\":141,\"value\":\"Flood Summary Name\"},{\"widgetControllerId\":142,\"value\":\"Did the property flood?\"},{\"widgetControllerId\":143,\"value\":\"no\"}]}]".utf8
let json = try! JSONSerialization.jsonObject(with: Data(str), options: [])
print(json)
This type of issue can also occur if you have a misconfigured server or your server is unreachable. If you receive this type of error from JSON deserialization you may try converting the data to a string and print it out. It may reveal an error like "502 Bad Gateway"

How to parse JSON data in Swift 3? [duplicate]

This question already has answers here:
Correctly Parsing JSON in Swift 3
(10 answers)
Closed 5 years ago.
I need to get my GPS location from mySQL by PHP in Swift 3. I tried to write the code for get data but it still not work, could you advise me?
JSON Data from PHP:
[{"id":"3752","latitude":"11.2222","longitude":"111.2222","Speed":"0.000000","Volt":"3.97","Percent":"87.000000","Dates":"2017-03-07 22:53:32"}]
Swift 3 code:
import UIKit
//-------- import google map library --------//
import GoogleMaps
import GooglePlaces
class ViewController: UIViewController , GMSMapViewDelegate {
var placesClient: GMSPlacesClient!
override func viewDidLoad() {
super.viewDidLoad()
var abc : String = String()
//-------- Google key for ios --------//
GMSServices.provideAPIKey("XXXXXXXXXX")
GMSPlacesClient.provideAPIKey("XXXXXXXXX")
//--------set URL --------//
let myUrl = URL(string: "http://www.myweb/service.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = "";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Now we can access value of latiutde
let latitude= parseJSON["latitude"] as? String //<---- Here , which i need latitude value
print("latitude = \(latitude)")
}
} catch {
print(error)
}
}
task.resume()
}
I tried to write the code but it show the errors on debug output
let responseString = String(data: data, encoding: .utf8 )
let str = String(data: data, encoding: .utf8 )
let data2 = str?.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data2!, options: []) as! [String: AnyObject]
if let names = json["latitude"] as? [String] {
print(names)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
Error message
Could not cast value of type '__NSSingleObjectArrayI' (0x1065fad60) to
'NSDictionary' (0x1065fb288).
Try casting the json object to a Swift representation directly for a more 'Swifty' access of the underlying data. So you don't need to fuss around with NSNumber etc.
guard let json = JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [[String: String]] else { return }
guard json.count > 0 else { return }
guard let lattitude = json[0]["lattitude"] else { return }
print("Lattitude received: \(lattitude)")
If you are not sure you'll have a [String: String] object array, you can replace it with a [String: Any] in the cast, then all you need to do is check the type with an optional cast in reading the lattitude. You could add a chained optional then checking for isEmpty to check whether its the lattitude value you want or something went wrong.
I would also advice to pretty much never use ! in your code, try to rely more on optional chaining and guard statements.
Guard statement introduction
Note: a single line guard statement isn't very verbose and might make it very difficult to debug your application. Consider throwing errors or some more debug printing in the body of the guard statement.