Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to display JSON (well formatted) in UITextView or UIWebView in iOS

Tags:

json

ios

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,

like image 580
user1060551 Avatar asked Jun 28 '15 13:06

user1060551


People also ask

What is UITextView used for?

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.

How to render bold text in uilabel or UITextView?

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

How do I display multiple text styles in UITextView?

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.

Is wkwebview the only way to Present HTML string?

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.


1 Answers

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

pretty printed JSON String

like image 183
nRewik Avatar answered Nov 05 '22 23:11

nRewik