I need to display JSON in my iPhone app. Currently I am getting unformatted JSON - like one big string with no indentation.
What would be the best way to display this?
Thanks,
UITextView supports the display of text using custom style information and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document.
To render this text properly in UILabel or UITextView, you need to convert it to NSAttributedString. NSAttributedString has built-in support for this conversion. First, we need to convert HTML string to Data. let htmlString = "This is a <b>bold</b> text." let data = htmlString.data(using: .utf8)!
UITextView supports the display of text using custom style information and also supports text editing. You typically use a text view to display multiple lines of text, such as when displaying the body of a large text document. This class supports multiple text styles through use of the attributedText property.
When you work with an API, there would be a time when your backend wants to control a text style. HTML is the most common format for this kind of job. Do you know that WKWebView is not the only way to present HTML string? You can render HTML string directly on UILabel and UITextView. You can easily support sarunw.com by checking out this sponsor.
to get formatted JSON string.
The solution is to create JSON Object from JSON string,
and then convert the JSON object back to JSON String, using .PrettyPrinted
option.
The code is
let jsonString = "[{\"person\": {\"name\":\"Dani\",\"age\":\"24\"}},{\"person\": {\"name\":\"ray\",\"age\":\"70\"}}]"
var error: NSError?
//1. convert string to NSData
let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
//2. convert JSON data to JSON object
let jsonObject:AnyObject = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error)!
//3. convert back to JSON data by setting .PrettyPrinted option
let prettyJsonData = NSJSONSerialization.dataWithJSONObject(jsonObject, options: .PrettyPrinted, error: &error)!
//4. convert NSData back to NSString (use NSString init for convenience), later you can convert to String.
let prettyPrintedJson = NSString(data: prettyJsonData, encoding: NSUTF8StringEncoding)!
//print the result
println("\(prettyPrintedJson)")
The result will look like this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With