0

我正在 xCode 中制作应用程序。我有一个从 .json 文件加载 JSON 数据的方法。这很好用,我的视图控制器向我显示了 JSON 对象(解析后)。代码是:

- (void) loadJsonData
{
//Create an URL
NSURL *url = [NSURL URLWithString:@"http://www....json"];

//Sometimes servers return a wrong header. Use this to add a new accepted type
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:@"application/x-javascript"]];

//Create a request object with the url
NSURLRequest *request = [NSURLRequest requestWithURL:url];

//Create the JSON operation. The ^ blocks are executed when loading is done.
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request     success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {

    //Do something with the JSON data, like parsing
    [self parseJSONData:JSON];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    //Do something with the error
    NSLog(@"Error :%@",response);

}];

//Start the operation
[operation start];
}

但现在我想使用现有 .php 文件中的 JSON 对象。我更改了“http://www ....php”中的 URL。我没有错误,但它不加载 JSON。我的视图控制器不显示数据。我试图更改代码中的许多内容,但没有任何效果。如果我使用 .php 而不是 .json url,有人可以帮助我提供 loadJsonData 的确切代码。

提前致谢!

4

1 回答 1

0

我希望它会帮助你。


我在我的项目中使用以下功能。

PHP首先从以下获取json字符串

-(NSString *)httpRequest:(NSURL *)url {

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    NSString *userAgent = [NSString stringWithFormat:@"myProject-IOS"];
    [request setValue:userAgent forHTTPHeaderField:@"User-Agent"];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

    [request setHTTPMethod:@"GET"];

    [request setTimeoutInterval:25];

    NSURLResponse *response;

    NSData *dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    NSString *stringReply = [[NSString alloc] initWithData:dataReply encoding:NSASCIIStringEncoding];

    return stringReply;
}

NSString *link = @"http://domain.com/mypage.php";
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",link]];
NSString *response = [NSString stringWithString:[R httpRequest:url]];

使用SBSON将 json 字符串解析为 NSDictionary 后,如下所示

-(NSMutableDictionary *) parse:(NSString *)str {
    SBJSON *parser = [[SBJSON alloc] init];
    NSMutableDictionary *results = [parser objectWithString:str error:nil];
    //[parser release];

    return results;
}

NSDictionary *results = [R parse:response];

我的 PHP 页面如下所示

<?php

$array = array();

$array1 = array("a"=>"A", "b"=>"B", "c"=>"C");
$array2 = array("x"=>"X", "y"=>"X", "z"=>"Z");
$array3 = array("p"=>"P", "q"=>"Q", "r"=>"R");

$array[] = $array1;
$array[] = $array2;
$array[] = $array3;

echo json_encode($array);

?>
于 2013-10-24T10:29:59.940 回答