Xcode 解析 Json [英] Xcode Parse Json

查看:46
本文介绍了Xcode 解析 Json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以这是我从 url 获取 post json 数组的代码

So this is my code to get a post json array from a url

// SENDING A POST JSON
    NSString *post = [NSString stringWithFormat:@"plm=1"];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString:@"http://muvieplus.com/testjson/test.php"]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];


    NSURLResponse *requestResponse;
    NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];

    NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
    NSLog(@"%@", requestReply);

当我运行它时,我收到了 requestReply

When i run it i got the requestReply

2014-11-07 14:22:15.565 JsonApp[1849:60b] 
{
    {"employees":[
    {"firstName":"John", "lastName":"Doe"}, 
    {"firstName":"Anna", "lastName":"Smith"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

我如何解析这个json?有什么帮助吗?

How can i parse this json ? Any help please ?

推荐答案

使用 NSJSONSerialization 类从 JSON 数据中获取对象.

Use the NSJSONSerialization class to get an object from JSON data.

NSError *error;
NSDictionary *requestReply = [NSJSONSerialization JSONObjectWithData:[requestHandler bytes] options:NSJSONReadingAllowFragments error:&error]
if (requestReply) {
    //use the dictionary
}
else {
    NSLog("Error parsing JSON: %@", error);
}

这将返回一个包含 JSON 中所有对象的字典(取决于数据,它可能是一个数组),然后您可以使用它来构建您自己的对象或其他任何对象.

This will return a dictionary (depending on the data, it could be an array) containing all the objects in the JSON, which you can then use to build an object of your own or whatever.

我建议调查异步请求的使用,可能使用 NSURLSession 或像 AFNetworking 这样的第三方库,因为这将使您的应用程序响应更快.您甚至不应该使用同步 API 加载本地文件,更不用说发出网络请求,因为您的应用程序在获得响应之前将无法执行任何其他操作(在当前线程上),这可能是一个非常很长一段时间,尤其是当人们使用蜂窝数据时.

I would suggest investigating the use of asynchronous requests, probably using NSURLSession or a third party library like AFNetworking, as this will make your app more responsive. You shouldn't even load a local file using the synchronous APIs, let alone make a network request, as your app won't be able to do anything else (on the current thread) until it gets a response, which could be a very long time, particularly when people are using cellular data.

这篇关于Xcode 解析 Json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆