[英]iOS JSON Parse not working (returns null dictionary)
我使用NSJSONSerialization
的JSONObjectWithData:data options: error:
解析從服務器返回的JSON數據。
現在,對於options參數,我使用: NSJSONReadingAllowFragments
。 您可以在下面查看並查看實際的JSON(我認為問題出在哪里)。
我收到的錯誤消息是:
錯誤域= NSCocoaErrorDomain代碼= 3840“操作無法完成。(可可錯誤3840。)”(字符0周圍的無效值。)UserInfo = 0x6895da0 {NSDebugDescription =字符0周圍的無效值。}
知道如何解決嗎?
JSON =
{"name":"Johan Appleseed",
"email":"j.appleseed@emuze.co",
"phone":"+4121876003",
"accounts":{
"facebook":[true,1125],
"twitter":[false,null],
"homepage":[true,"http:\/\/johnAplleseed.com\/index.html"]}}
可能您有一些看不見的無法打印的角色。 嘗試這個:
NSData *jsonData = ...
const unsigned char *ptr = [data bytes];
for(int i=0; i<[data length]; ++i) {
unsigned char c = *ptr++;
NSLog(@"char=%c hex=%x", c, c);
}
為了驗證您在數據的開頭或結尾處沒有不可打印的字符。
編輯:澄清一下,只需在JSON字典上運行以上內容即可-解析失敗的字典。
Ive明智地發現了問題所在,因為URL的返回是一個HTML頁面,在實際響應周圍附加了所有這些html,head和body標簽,因此無法對其進行解析。 這是有關如何從響應中刪除HTML標記(將其更改為字符串后)的很好的問答: 從iPhone上的NSString刪除HTML標記
我有一段時間遇到同樣的問題,我只是發現,如果我要從網頁中提取數據(例如PHP頁面),則該頁面中不應有任何HTML標記。 像這樣的結構:
<html>
<body>
<?php
?>
</body>
</html>
將破壞您的結果。 變成:
<?php
?>
為我工作。
已經有一段時間了,但是打印數據的一種更簡單的方法是:
NSLog(@“%@”,[[NSString alloc] initWithData:data編碼:NSUTF8StringEncoding]);
一種方法是,您可以通過發布請求解析jsondata
-(void)callWebserviceList
{
spinner.hidden=NO;
NSString *bodyData = @"code_request=monuments_list&asi_id=1";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://asicircles.com/server_sync.php"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
connection1 = [NSURLConnection connectionWithRequest:postRequest委托人:self];
if(connection1 !=nil)
{
////NSLog(@"%@",postRequest);
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([connection isEqual:connection1 ])
{
[responseData setLength:0];
}else if ([connection isEqual:connection2 ])
{
[responseData1 setLength:0];
}
}-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if ([connection isEqual:connection1 ])
{
[responseData appendData:data];
}else if ([connection isEqual:connection2 ])
{
[responseData1 appendData:data];
}
//**check here for responseData & also data**
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"%@",[NSString stringWithFormat:@"Connection failed: %@", [error description]]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if ([connection isEqual:connection1 ])
{
spinner.hidden=YES;
NSError *error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSMutableArray *arrdata=[json objectForKey:@"message"];
NSLog(@"code is%@", json);
for (int i=0; i< arrdata.count; i++)
{
[arrDetails addObject:[[arrdata objectAtIndex:i]objectForKey:@"details"]];
[arrImageUrl addObject:[[arrdata objectAtIndex:i]objectForKey:@"image"]];
[arrLat addObject:[[arrdata objectAtIndex:i]objectForKey:@"lat"]];
[arrLongi addObject:[[arrdata objectAtIndex:i]objectForKey:@"longi"]];
[arrName addObject:[[arrdata objectAtIndex:i]objectForKey:@"name"]];
[arrLoc addObject:[[arrdata objectAtIndex:i]objectForKey:@"location"]];
[arrID addObject:[[arrdata objectAtIndex:i]objectForKey:@"id"]];
NSLog(@"code is%@",[[arrdata objectAtIndex:i]objectForKey:@"details"]);
NSLog(@"code is%@",[arrImageUrl objectAtIndex:i]);
}
if (arrName.count > 0)
{
[self addscrollView];
}
}else if ([connection isEqual:connection2 ])
{
}
}
您還可以在iOS中按塊訪問json數據的url
#define kBgQueue dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:
@"http://api.kivaws.org/v1/loans/search.json?status=fundraising"] //2
我們需要做的第一件事是從Web下載JSON數據。 幸運的是,有了GCD,我們可以在一行代碼中做到這一點! 將以下內容添加到ViewController.m中:
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:@selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:@"loans"]; //2
NSLog(@"loans: %@", latestLoans); //3
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.