21

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

[

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

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

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

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

并这样做:

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

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

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

  • 所以,在他们改变底层结构之前,我有什么办法可以让它iOS像他们一样javascript工作website吗?

任何帮助/建议都会对我很有帮助。

4

14 回答 14

42

正确的 JSON 应该看起来像:

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

但是,如果您坚持使用问题中提供的格式,则需要使字典可变,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);
    }
}
于 2013-10-16T13:49:41.880 回答
13

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

- (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");
        }
    }

}
于 2014-03-19T05:57:48.097 回答
4

正如上面人们所说,您必须首先使用 或来NSJSONSerialization反序列JSON化为可用的数据结构。NSDictionaryNSArray

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

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

- (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",
            };
}

然后通过执行以下操作执行解析:

- (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];
}

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

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

于 2014-03-11T08:34:40.153 回答
3

// ----------------- 本地文件的 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];

//------------ 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];

//------------ 通过异步获取 urlfile 的 json----------

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

//------------- urlfile的json同步----------

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

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

[tableview reloadData];
} ;
于 2015-10-10T04:11:27.000 回答
3
//-------------- 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);
}
于 2015-10-09T18:07:46.293 回答
2
  • 您可能总是jsonData在将其交付给NSJSONSerialization. 或者您可以使用字符串 got 构造另一个字符串json object来获取array.

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

于 2013-10-16T13:17:55.703 回答
1
 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"];
于 2014-12-16T09:40:55.323 回答
1

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

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

于 2013-10-16T13:29:26.527 回答
1
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);
    }
于 2015-10-09T16:11:23.720 回答
1

可能这会对你有所帮助。

- (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"]];

    }

}
于 2016-01-21T09:27:34.877 回答
0
#define FAVORITE_BIKE @"user_id=%@&bike_id=%@"
@define FAVORITE_BIKE @"{\"user_id\":\"%@\",\"bike_id\":\"%@\"}"
NSString *urlString = [NSString stringWithFormat:@"url here"];
NSString *jsonString = [NSString stringWithFormat:FAVORITE_BIKE,user_id,_idStr];
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0)
{
    NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *resDict =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
}
于 2016-11-28T08:53:16.973 回答
0

JSON默认方法:

+ (NSDictionary *)stringWithUrl:(NSURL *)url postData:(NSData *)postData httpMethod:(NSString *)method
{
    NSDictionary *returnResponse=[[NSDictionary alloc]init];

    @try
    {
        NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url
                                                                  cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                              timeoutInterval:180];
        [urlRequest setHTTPMethod:method];

        if(postData != nil)
        {
            [urlRequest setHTTPBody:postData];
        }

        [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [urlRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
        [urlRequest setValue:@"text/html" forHTTPHeaderField:@"Accept"];

        NSData *urlData;
        NSURLResponse *response;
        NSError *error;
        urlData = [NSURLConnection sendSynchronousRequest:urlRequest
                                        returningResponse:&response
                                                    error:&error];
        returnResponse = [NSJSONSerialization
                          JSONObjectWithData:urlData
                          options:kNilOptions
                          error:&error];
    }
    @catch (NSException *exception)
    {
        returnResponse=nil;
    }
    @finally
    {
        return returnResponse;
    }
}

退货方式:

+(NSDictionary *)methodName:(NSString*)string{
    NSDictionary *returnResponse;
    NSData *postData = [NSData dataWithBytes:[string UTF8String] length:[string length]];
    NSString *urlString = @"https//:..url....";
    returnResponse=[self stringWithUrl:[NSURL URLWithString:urlString] postData:postData httpMethod:@"POST"];    
    return returnResponse;
}
于 2015-11-26T17:00:20.507 回答
0

@property NSMutableURLRequest * urlReq;

@property NSURLSession * 会话;

@property NSURLSessionDataTask * 数据任务;

@property NSURLSessionConfiguration * sessionConfig;

@property NSMutableDictionary * appData;

@property NSMutableArray * valueArray; @property NSMutableArray * keysArray;

  • (void)viewDidLoad { [超级 viewDidLoad]; self.valueArray = [[NSMutableArray alloc]init]; self.keysArray = [[NSMutableArray alloc]init]; self.linkString = @" http://country.io/names.json "; [自我获取数据];

-(void)getData
{ self.urlReq = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:self.linkString]];

self.sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];

self.session = [NSURLSession sessionWithConfiguration:self.sessionConfig];

self.dataTask = [self.session dataTaskWithRequest:self.urlReq completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    self.appData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

    NSLog(@"%@",self.appData);
    self.valueArray=[self.appData allValues];
    self.keysArray = [self.appData allKeys];


}];
[self.dataTask resume];
于 2016-10-20T04:11:26.533 回答
-1
-(void)responsedata
{

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:replacedstring]];

    [request setHTTPMethod:@"GET"];
    NSURLSessionConfiguration *config=[NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session=[NSURLSession sessionWithConfiguration:config];
    NSURLSessionDataTask *datatask=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"ERROR OCCURE:%@",error.description);
        }
        else
        {
            NSError *error;
            NSMutableDictionary *responseDict=[[NSMutableDictionary alloc]init];
            responseDict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];


            if (error==nil)
            {


             // use your own array or dict for fetching as per your key..  


                _responseArray =[[NSMutableArray alloc]init];

                _geometryArray=[[NSMutableArray alloc]init];



                _responseArray=[responseDict valueForKeyPath:@"result"];

                referncestring =[[_photosArray objectAtIndex:0]valueForKey:@"photo_reference"];

                _geometryArray=[_responseArray valueForKey:@"geometry"];
               // _locationArray=[[_geometryArray objectAtIndex:0]valueForKey:@"location"];
                _locationArray=[_geometryArray valueForKey:@"location"];
                latstring=[_locationArray valueForKey:@"lat"];
                lngstring=[_locationArray valueForKey:@"lng"];


        coordinates = [NSMutableString stringWithFormat:@"%@,%@",latstring,lngstring];




            }

        }

        dispatch_sync(dispatch_get_main_queue(), ^
                      {



                         // call the required method here..

                      });




    }];
    [datatask resume];   //dont forget it

    }
于 2016-08-20T13:13:53.200 回答