My Json string is not decoding using JSONSerialization.jsonObject() - json

I'm receiving a valid Json string from my HTTP request which looks like this
"[{
"id”:10,
"user_id":"77da74e6-3e03-403d-9c1a-91f231233515”,
"friend_user_id":"fc879bf5-c53d-4a4e-b3a4-dab7a8266a2r”,
"name":"Tommie Smith”,
"type":"active”,
"created_at":"2018-05-02 14:53:09",
"updated_at":"2018-05-02 14:53:09",
"friend_user":{
"id":"fc879bf5-c53d-4a4e-b3a4-dab7a8266a2r",
"first_name”:”Allen”,
"last_name”:”Williams”,
"email”:”allen.williams#example.org",
"date_of_birth":"1996-03-05 00:00:00",
"created_at":"2018-05-02 14:53:07",
"updated_at":"2018-05-02 14:53:07",
"deleted_at":null
}
},
{
"id”:11,
"user_id":"77da74e6-3e03-403d-9c1a-91f231233515”,
"friend_user_id":"96990d13-372e-46f7-9187-94988954455b”,
"name":"Mr. Thomas Atkins”,
"type":"not",
"created_at":"2018-05-02 14:53:10",
"updated_at":"2018-05-02 14:53:10",
"friend_user":{
"id":"96990d13-372e-46f7-9187-94988954455b",
"first_name”:”Trevor”,
"last_name”:”Wright”,
"email”:”trevor.wright#example.net",
"date_of_birth":"1983-07-27 00:00:00",
"created_at":"2018-05-02 14:53:08",
"updated_at":"2018-05-02 14:53:08",
"deleted_at":null
}
}]"
I know that this is what I'm receiving as I'm using the following code to return a string with my data
let string = String(data: data, encoding: String.Encoding.utf8)
However, when I use the code below to parse my data, json returns nil
let json = try JSONSerialization.jsonObject(with: data) as? [String: AnyObject]
What is wrong with this statement?

Please (learn to) read the JSON, it's pretty easy. There are only 2 (two!) different collection types:
{} is dictionary, in Swift [String: Any].
[] is array, in Swift [Any] but in most cases an array of dictionaries [[String: Any]].
so the JSON is clearly an array. In Swift 3+ a JSON value is never AnyObject
let json = try JSONSerialization.jsonObject(with: data) as? [[String: Any]]
Note:
The mistaken double quotes are not the error reason, otherwise jsonObject(with would throw an error

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.

Cannot convert Data to NSDictionary

I'm trying to convert data from URLSession to a NSDictionary but it fails when converting the data to dictionary.
Following:
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
print(json ?? "NotWorking")
outputs
(
{
babyId = 1;
id = 17;
timestamp = "2018-06-30 09:23:27";
}
)
But when I try to convert it into a Dictionary with following it outputs nil.
let json = try? JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
The webpage outputs
[{"id":"17","babyId":"1","timestamp":"2018-06-30 09:23:27"}]
Where does the error occurs?
[ ] means array in JSON. { } means dictionary. You have an array of dictionary. Note that when you print an array in Swift, you will see ( ).
Don't use NSArray or NSDictionary in Swift without a very clearly understood and specific reason. Use a Swift array and dictionary of the proper types.
Your code should be:
do {
if let results = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] {
// results is now an array of dictionary, access what you need
} else {
print("JSON was not the expected array of dictonary")
}
} catch {
print("Can't process JSON: \(error)")
}
And really you shouldn't be using data! either. Somewhere above this you should have a if let data = data {

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"

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

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

swift byte[] in json object

I'm trying to serialize json object like this
let jsonObject: [String: Any] = [
"Description":problemDescription.text!,
"Photo": byteArray
]
let jsonData = try! NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted)
but I'm getting this type of error:
swift 2 argument type string any does not conform to expected type any object.
Any ideas?
update: It seems that when I'm printing json object after this line
let jsonData = try! NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted)
that that conversion to byte[] occurs itself. At least seems that way in console debug.