iOS 7 中的 JSON 解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19404327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 02:22:09  来源:igfitidea点击:

JSON Parsing in iOS 7

iosobjective-cjsonnsmutablearraynsarray

提问by Ajeet

I am creating an app for as existing website. They currently has the JSON in the following format :

我正在为现有网站创建一个应用程序。他们目前拥有以下格式的 JSON:

[

   {
       "id": "value",
       "array": "[{\"id\" : \"value\"} , {\"id\" : \"value\"}]"
   },
   {
       "id": "value",
       "array": "[{\"id\" : \"value\"},{\"id\" : \"value\"}]"
   } 
]

which they parse after escaping the \ character using Javascript.

他们在使用 Javascript 转义 \ 字符后对其进行解析。

My problem is when i parse it in iOS using the following command :

我的问题是当我使用以下命令在 iOS 中解析它时:

NSArray *result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&localError];

and do this :

并这样做:

NSArray *Array = [result valueForKey:@"array"];

Instead of an ArrayI got NSMutableStringobject.

而不是Array我得到了NSMutableString对象。

  • The website is already in production so I just cant ask them to change their existing structure to return a proper JSONobject. It would be a lot of work for them.

  • So, until they change the underlying stucture, is there any way i can make it work in iOSlike they do with javascripton their website?

  • 该网站已经在生产中,所以我不能要求他们更改现有结构以返回正确的JSON对象。这对他们来说将是很多工作。

  • 那么,在他们改变底层结构之前,有什么办法可以让它iOS像他们javascript在他们的website.

Any help/suggestion would be very helpful to me.

任何帮助/建议对我都非常有帮助。

回答by Rob

The correct JSON should presumably look something like:

正确的 JSON 大概应该是这样的:

[
    {
        "id": "value",
        "array": [{"id": "value"},{"id": "value"}]
    },
    {
        "id": "value",
        "array": [{"id": "value"},{"id": "value"}]
    }
]

But, if you're stuck this the format provided in your question, you need to make the dictionary mutable with NSJSONReadingMutableContainersand then call NSJSONSerializationagain for each of those arrayentries:

但是,如果您坚持使用问题中提供的格式,则需要使字典可变,NSJSONReadingMutableContainers然后NSJSONSerialization为每个array条目再次调用:

NSMutableArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error)
    NSLog(@"JSONObjectWithData error: %@", error);

for (NSMutableDictionary *dictionary in array)
{
    NSString *arrayString = dictionary[@"array"];
    if (arrayString)
    {
        NSData *data = [arrayString dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        dictionary[@"array"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
        if (error)
            NSLog(@"JSONObjectWithData for array error: %@", error);
    }
}

回答by Rajesh Loganathan

Try this simple method....

试试这个简单的方法....

- (void)simpleJsonParsing
{
    //-- Make URL request with server
    NSHTTPURLResponse *response = nil;
    NSString *jsonUrlString = [NSString stringWithFormat:@"http://domain/url_link"];
    NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    //-- Get request and response though URL
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    //-- JSON Parsing
    NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"Result = %@",result);

    for (NSMutableDictionary *dic in result)
    {
         NSString *string = dic[@"array"];
        if (string)
        {
             NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
             dic[@"array"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        }
        else
        {
             NSLog(@"Error in url response");
        }
    }

}

回答by vilanovi

As people just said above, you must use the NSJSONSerializationto deserialise JSONinto usable data structures as NSDictionaryor NSArrayfirst.

随着人们只是上面说的,您必须使用NSJSONSerialization到deserialiseJSON成有用的数据结构NSDictionaryNSArray第一。

However, if you want to map the content of your JSONto your Objective-C objects, you will have to map each attribute from the NSDictionary/NSArrayto your object property. This might be a bit painful if your objects have many attributes.

但是,如果您想将您的内容映射JSON到您的 Objective-C 对象,您必须将每个属性从 映射NSDictionary/NSArray到您的对象属性。如果您的对象有很多属性,这可能会有点痛苦。

In order to automatise the process, I recommend you to use the Motiscategory on NSObject(a personal project) to accomplish it, thus it is very lightweight and flexible. You can read how to use it in this post. But just to show you, you just need to define a dictionary with the mapping of your JSONobject attributes to your Objective-C object properties names in your NSObjectsubclasses:

为了自动化该过程,我建议您使用(个人项目)上的Motis类别NSObject来完成它,因此它非常轻便灵活。您可以在这篇文章中阅读如何使用它。但只是为了向您展示,您只需要定义一个字典,将您的JSON对象属性映射到您的NSObject子类中的Objective-C 对象属性名称:

- (NSDictionary*)mjz_motisMapping
{
    return @{@"json_attribute_key_1" : @"class_property_name_1",
             @"json_attribute_key_2" : @"class_property_name_2",
              ...
             @"json_attribute_key_N" : @"class_property_name_N",
            };
}

and then perform the parsing by doing:

然后通过执行解析:

- (void)parseTest
{
    // Some JSON object
    NSDictionary *jsonObject = [...];

    // Creating an instance of your class
    MyClass instance = [[MyClass alloc] init];

    // Parsing and setting the values of the JSON object
    [instance mjz_setValuesForKeysWithDictionary:jsonObject];
}

The setting of the properties from the dictionary is done via KeyValueCoding(KVC) and you can validate each attribute before setting it via KVCvalidation.

字典中的属性设置是通过KeyValueCoding(KVC) 完成的,您可以在通过KVC验证设置之前验证每个属性。

Hoping it helps you as much it helped me.

希望它对你有帮助,就像它对我的帮助一样。

回答by ashvin

//-------------- get data url--------

NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://echo.jsontest.com/key/value"]];

NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(@"response==%@",response);
NSLog(@"error==%@",Error);
NSError *error;

id jsonobject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

if ([jsonobject isKindOfClass:[NSDictionary class]]) {
    NSDictionary *dict=(NSDictionary *)jsonobject;
    NSLog(@"dict==%@",dict);
}
else
{
    NSArray *array=(NSArray *)jsonobject;
    NSLog(@"array==%@",array);
}

回答by ashvin

// ----------------- json for localfile---------------------------

// ----------------- 本地文件的 json ---------------------------

NSString *pathofjson = [[NSBundle mainBundle]pathForResource:@"test1" ofType:@"json"];
NSData *dataforjson = [[NSData alloc]initWithContentsOfFile:pathofjson];
arrayforjson = [NSJSONSerialization JSONObjectWithData:dataforjson options:NSJSONReadingMutableContainers error:nil];
[tableview reloadData];

//------------- json for urlfile-----------------------------------

//------------ urlfile 的 json------------------------ ---

NSString *urlstrng = @"http://www.json-generator.com/api/json/get/ctILPMfuPS?indent=4";
NSURL *urlname = [NSURL URLWithString:urlstrng];
NSURLRequest *rqsturl = [NSURLRequest requestWithURL:urlname];

//------------ json for urlfile by asynchronous----------------------

//------------ json for urlfile by asynchronous----------------------

[NSURLConnection sendAsynchronousRequest:rqsturl queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    arrayforjson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    [tableview reloadData];
}];

//------------- json for urlfile by synchronous----------------------

//------------ json for urlfile by 同步--------------

NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:rqsturl returningResponse:nil error:&error];

 arrayforjson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];

[tableview reloadData];
} ;

回答by pinxue

  • You may always unescape the jsonDatabefore deliver it to NSJSONSerialization. Or you may use the string got to construct another json objectto get the array.

  • NSJSONSerializationis doing right, the value in your example should be a string.

  • 您可能总是 unescape the jsonDatabefore 将其交付给NSJSONSerialization. 或者,您可以使用 got 来构造另一个字符串json object来获取array.

  • NSJSONSerialization做得对,您示例中的值应该是一个字符串。

回答by Abizern

As another answer has said, that value is a string.

正如另一个答案所说,该值是一个字符串。

You can get around it by turning that string into data, as it seems to be a valid json string and then parse that json data object back into an array which you can add to your dictionary as the value for the key.

您可以通过将该字符串转换为数据来绕过它,因为它似乎是一个有效的 json 字符串,然后将该 json 数据对象解析回一个数组,您可以将其添加到您的字典中作为键的值。

回答by abc

 NSError *err;
    NSURL *url=[NSURL URLWithString:@"your url"];
    NSURLRequest *req=[NSURLRequest requestWithURL:url];
    NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:&err];
    NSDictionary *json=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSArray * serverData=[[NSArray alloc]init];
    serverData=[json valueForKeyPath:@"result"];

回答by ashvin

NSString *post=[[NSString stringWithFormat:@"command=%@&username=%@&password=%@",@"login",@"username",@"password"]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.blablabla.com"]];

   [request setHTTPMethod:@"POST"];

   [request setValue:@"x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    [request setHTTPBody:[NSData dataWithBytes:[post UTF8String] length:strlen([post UTF8String])]];

   NSData *data=[NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    id jsonobject=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

    if ([jsonobject isKindOfClass:[NSDictionary class]])
    {

        NSDictionary *dict=(NSDictionary *)jsonobject;
        NSLog(@"dict==%@",dict);

    }
    else
    {

        NSArray *array=(NSArray *)jsonobject;
        NSLog(@"array==%@",array);
    }

回答by Nilesh Parmar

May be this will help you.

可能这会帮助你。

- (void)jsonMethod
{
    NSMutableArray *idArray = [[NSMutableArray alloc]init];
    NSMutableArray *nameArray = [[NSMutableArray alloc]init];
    NSMutableArray* descriptionArray = [[NSMutableArray alloc]init];

    NSHTTPURLResponse *response = nil;
    NSString *jsonUrlString = [NSString stringWithFormat:@"Enter your URL"];
    NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];


    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];

    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"Result = %@",result);


    for (NSDictionary *dic in [result valueForKey:@"date"])
    {
        [idArray addObject:[dic valueForKey:@"key"]];
        [nameArray addObject:[dic valueForKey:@"key"]];
        [descriptionArray addObject:[dic valueForKey:@"key"]];

    }

}