Reputation: 40237
I wonder if there is any way to print exact JSON string in pretty format while logging. I was printing a http request header fields like,
let jsonData = try JSONSerialization.data(withJSONObject: dictionary, options: .prettyPrinted)
let jsonString = String(bytes: jsonData, encoding: String.Encoding.utf8)
MyLogUtil.logVerbose(message: "\(String(describing: jsonString))")
But instead of printing expected logs like below,
{
"user": {
name: "Test",
age: "30"
}
}
Its printing something like,
{\n"user": {\nname: "Test",\n\nage: "30"\n}\n}\n
How to get rid of this issue?
EDIT: @AwaisFayyaz
func requestTest() -> Void {
let task = URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: Any]
if let userDict = json["user"] as? NSDictionary {
print(userDict)
}
}
catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
task.resume()
}
Above code got crashed!
Upvotes: 0
Views: 3413
Reputation: 2415
Suppose this is your input string that you want to print in pretty format. Then
let str = "{\"user\":{\"name\":\"Test\",\"age\":\"30\"} }"
Then use
let data = str.data(using: String.Encoding.utf8, allowLossyConversion: false)!
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as! [String: AnyObject]
if let userDict = json["user"] as? NSDictionary {
print(userDict)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
I have implemented the code. See the console output in the image
@Answer to Edit
Your code is crashing because JSON is returning An Array and you are force casting as [String: Any] (not possible). Instead cast it as NSArray
use the following code snippet in this case
func requestTest() -> Void {
let task = URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in
do {
//cast it as Array
let usersArray = try JSONSerialization.jsonObject(with: data!, options: []) as! NSArray
for userDictAny in usersArray {
//cast the type of userDictAny to NSDictionary
guard let userDict = userDictAny as? NSDictionary else {
print("Error. Count not cast as NSDictionary. Going to return")
return
}
print("\n\n\(userDict)\n\n")
//additionaly, if you want to get value of individual fields from userDict
if let userId = userDict["userId"] as? Int64 {
print("Value of userID \(userId)")
}
//in the same way get more values if you want from userDict
}
}
catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
task.resume()
}
Note that original ordering of data will not be preserved because it is a dictionary. But you can see your output in nice format
Output Snapshot of running code
Upvotes: 1