Museer Ahamad Ansari
Museer Ahamad Ansari

Reputation: 5523

Show JSON data in text View in Swift

i am getting response from server like this

[{

    "images":[{
       "title_de":"sdfs",
       "title_it":"dsdfs",
       "title_fr":"dfsf",
       "approved":"true",
       "title_ru":"sdsf",
       "title_ko":"sdfs",
       "title_jp":"sfsdf",
       "title_es":"sdfs",
       "title_pt":"dfs",
       "folder_id":29,
       "title_en":"title image",
       "title_hi":"sdfss",
       "image_used_count":"0",
       "updatedtime":"1470641760",
       "folder_empty":"false",
       "id":115,
       "is_folder":"false"
   },

   {
       "title_de":"tests Ashdod",
       "title_it":"test cv",
       "title_fr":"tests Asgard",
       "approved":"true",
       "title_ru":"testvxcv",
       "title_ko":"testvcxv",
       "title_jp":"tests cv",
       "title_es":"testvcxv",
       "title_pt":"test cox",
       "folder_id":19,
       "title_en":"testsds",
       "title_hi":"testvxcv",
       "image_used_count":"0",
       "updatedtime":"1470401264",
       "folder_empty":"false",
       "id":99,
       "is_folder":"false"
   }]
}]

Now i want to show this response on text view as it is and here is my code

self.tv_response.text = String(format:"%@", JSON as! String )

but getting an error

Could not cast value of type '__NSCFArray' (0x1025a8ae0) to 'NSString' (0x101c13b20).

I also try

self.tv_response.text = NSString(format:"%@", JSON as! String )

but not working please help me ...

Upvotes: 3

Views: 2235

Answers (3)

DSAjith
DSAjith

Reputation: 362

NSString(format:"%@", JSON as! String )

here JSON file in not String file its an Array. You are unwrapping it(!).So use

String(format:"%@", JSON)

or else

self.tv_response.text = "\(JSON)"

Upvotes: -2

kabiroberai
kabiroberai

Reputation: 2913

You shouldn't be using String(format:_:) in Swift anyways. A better way to do it would be self.tv_response.text = "\(JSON)". This uses String Interpolation which lets you conveniently create a string out of any type of value.

However, if you must do it with String(format:_:), you can do the following: self.tv_response.text = String(format:"%@", JSON).

Upvotes: 1

Nirav D
Nirav D

Reputation: 72410

Your response is array so you can not directly convert it to string.

self.tv_response.text = "\(JSON as! NSArray)"

or

self.tv_response.text = "\(JSON as! [[String: AnyObject]])"

Upvotes: 4

Related Questions