在文本中显示 JSON 数据 在 Swift 中查看

Show JSON data in text View in Swift

我收到这样的服务器响应

[{

    "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"
   }]
}]

现在我想在文本视图中按原样显示此响应,这是我的代码

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

但出现错误

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

我也试试

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

但是不工作请帮助我...

您的回复是 array,因此您不能直接将其转换为 string

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

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

无论如何你都不应该在 Swift 中使用 String(format:_:)。更好的方法是 self.tv_response.text = "\(JSON)"。这使用 String Interpolation,它可以让您方便地从任何类型的值中创建一个字符串。

但是,如果您 必须 使用 String(format:_:) 执行此操作,您可以执行以下操作:self.tv_response.text = String(format:"%@", JSON).

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

此处 JSON 文件不是字符串文件,而是一个数组。 你正在打开它(!)。所以使用

String(format:"%@", JSON)

否则

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