我遇到以下问题:
我想将我的iPhone-App与服务器上的数据库连接。因此,我使用一些(简单).php文件来管理对数据库的访问。插入新数据已经可以了,但是我很难将获取的数据转换为NSMutableArray:
NSURL *contentURL = [NSURL URLWithString:[kHOSTURL stringByAppendingString:kGETBarsURL]];
NSLog(@"URL : %@", contentURL);
NSData *contentData = [NSData dataWithContentsOfURL:contentURL];
NSLog(@"Data : %@", contentData);
NSError *e = nil;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:contentData
options:kNilOptions
error:&e];
NSLog(@"JSON : %@", jsonArray);
NSLog(@"Error : %@", e);
输出是这样的(我是“XX”,简称为“Data:”):
2012-04-28 13:49:37.229 XX[14434:f803] URL : http://xx/getBars.php
2012-04-28 13:49:37.389 XX[14434:f803] Data : <5b7b2275 6e697175 65223a22 34222c22 4e616d65 223a2254 65737422 2c224465 7461696c 73223a22 54686973 49734154 65737422 7d2c7b22 ...>
2012-04-28 13:49:37.390 XX[14434:f803] JSON : (null)
2012-04-28 13:49:37.392 XX[14434:f803] Error : Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x6daa610 {NSDebugDescription=Garbage at end.}
如果我在浏览器中打开页面,则如下所示:
[{"unique":"4","Name":"Test","Details":"ThisIsATest"},
{"unique":"5","Name":"Test","Details":"ThisIsATest"},
{"unique":"6","Name":"Test","Details":"ThisIsATest"},
{"unique":"7","Name":"Test","Details":"ThisIsATest"},
{"unique":"8","Name":"Test","Details":"ThisIsATest"},
{"unique":"9","Name":"Test","Details":"ThisIsATest"},
{"unique":"10","Name":"Test","Details":"ThisIsATest"}]
我也尝试了NSJSONSerialization中的其他选项,但是没有用:(有人可以在这里帮助我吗?
2012-04-28 14:18:30.192 XX[14541:f803] Encoding : [{"unique":"4","Name":"Test","Details":"ThisIsATest"},{"unique":"5","Name":"Test","Details":"ThisIsATest"},{"unique":"6","Name":"Test","Details":"ThisIsATest"},{"unique":"7","Name":"Test","Details":"ThisIsATest"},{"unique":"8","Name":"Test","Details":"ThisIsATest"},{"unique":"9","Name":"Test","Details":"ThisIsATest"},{"unique":"10","Name":"Test","Details":"ThisIsATest"}]
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-16106315-6']);
_gaq.push(['_setDomainName', '.xx.de']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript';
ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(ga, s);
})();
</script>
最佳答案
很明显,您的末尾确实有“垃圾”。您有一个JavaScript块,尽管在浏览器中不可见,但仍从您的php脚本返回。删除它,您应该会很好。
关于ios - NSJSONSerialization-如何将JSON正确转换为NSArray?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10363274/