我目前正在使用 AFNetworking 从 Wordpress API 使用 JSON 网络服务。
这是我使用的格式:
[
{
id: 4,
title: "post1",
permalink: “http://www.example.com/test-post”,
content: “blah blah blah blah blah <iframe src="//player.vimeo.com/video/1010101?title=0&byline=0&portrait=0&color=ff5546" height="638" width="850" allowfullscreen="" frameborder="0"></iframe> more text blah blah <a href="http://example.com/wp-content/uploads/2014/01/testpic.png"><img class="aligncenter size-full wp-image-1180" alt="testpic" src="http://example.co/wp-content/uploads/2014/01/testpic.png" width="850" height="611" /></a>",
excerpt: " blah blah blah",
date: "2014-02-24 23:32:19",
author: "admin",
categories:
[
"Uncategorized"
],
tags: [ ]
},
{
id: 1,
title: "Hello world!",
permalink: “http://www.example.com/test-post”,
content: "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
excerpt: "Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!",
date: "2014-02-24 22:48:12",
author: "admin",
categories:
[
"Uncategorized"
],
tags: [ ]
}
]
我按如下方式使用它:
-(void)makeWordpressRequest
{
NSURL *URL = [NSURL URLWithString:@"http://example.com/feed/json"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
self.wordpress = responseObject;
[self.tableView reloadData];
NSLog(@"%@", responseObject);
} failure:nil];
[operation start];
}
现在这是我的问题。我可以成功解析和显示 JSON 的“content”字符串,但我还没有弄清楚如何从该字符串中删除视频的“iframe”和“a href”显示它。
有没有直接嵌入它们的方法?或者我可以通过编程方式将它们从 JSON 字符串中分离出来,然后以另一种方式嵌入它们吗?我目前正在使用 UITextView 来显示@"content"。
编辑:
不仅删除了 HTML,而且在可能的情况下还提供了一种正确嵌入它的方法..
谢谢你的帮助
最佳答案
您的 API 不应在 JSON 中为您提供 XML/HTML。*
理想情况下,您应该获取 API 来解决此问题,因为在 JSON 中解析 XML/HTML 会带来新的错误可能性。例如,可能存在字符编码问题、转义问题等。这是糟糕的 API 设计。看起来您正在使用 Wordpress,因此您可能想在此处发布一个单独的问题,了解如何修改 Wordpress JSON API 以获取应用程序中所需的 URL。
如果你真的不能修改API,你只好把字符串从JSON中取出来,然后通过NSScanner或NSXMLParser运行它来尝试挑选出你想要的部分。我会从 NSScanner 开始,因为它更简单,而且我猜你的 API 不能保证你会得到有效的 XML。 Here's some sample code to get your started .
最后,稍微偏离主题:您可能想要使用 AFNetworking 类 AFRequestOperationManager 而不是构建操作并立即启动它们。它可以使您的代码更简单、更高效。现在不急,只是想鼓励你看看。
*(可能;这条规则也有异常(exception)。如果您应该在 UIWebView 中显示内容,也许它是可以接受的。)
关于ios - 如何从 JSON 字符串解析 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22033099/