Xcode解析Json数据

时间:2013-05-14 08:19:38

标签: iphone ios6

以下我的代码工作正常,但突然间它停止了工作。谁能告诉我我做错了什么?

NSLog()的输出:

2013-05-14 16:06:35.475 Run.PH[1502:19a03] background = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] logo = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] json = (null)
2013-05-14 16:06:35.476 Run.PH[1502:19a03] welcome = (null)

代码:

- (void)viewDidLoad
{

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    NSString *urlString = [NSString stringWithFormat:@"http://run.ph/json/test_json_dyna.jsp"];

    NSURL *url = [NSURL URLWithString:urlString];

    NSData *data = [NSData dataWithContentsOfURL:url];

    if(data != nil)
    {

        NSError *error;

        _json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

        _welcomeMessage.text = [[_json objectForKey:@"welcome"] objectForKey:@"message"];

        NSString *background = [[_json objectForKey:@"welcome"] objectForKey:@"background"];

        NSString *logo = [[_json objectForKey:@"welcome"] objectForKey:@"logo"];


        NSLog(@"background = %@", background);
        NSLog(@"logo = %@", logo);
        NSLog(@"json = %@", _json);
        NSLog(@"welcome = %@", _welcomeMessage.text);


        NSURL *urlBackground = [NSURL URLWithString:background];
        NSData *dataBackground = [NSData dataWithContentsOfURL:urlBackground];

        [_background setImage:[UIImage imageWithData:dataBackground]];

        NSURL *urlLogo = [NSURL URLWithString:logo];
        NSData *dataLogo = [NSData dataWithContentsOfURL:urlLogo];

        [_logo setImage:[UIImage imageWithData:dataLogo]];
    }
    else
    {
        NSLog(@"Error!");
    }


    [self.view reloadInputViews];
}

1 个答案:

答案 0 :(得分:0)

只需NSLog你的URL响应你将得到你的json错误。 试试这个

NSString *respo = [NSString stringWithContentsOfURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
NSLog(@"Response - %@",respo);  

您的回复会返回“\ r”和换行符“\ n”。

检查

enter image description here

修改
现在您的网址工作正常,问题出在您的网络服务端。