JSON Parsing w iOS 7

Tworzę aplikację dla istniejącej strony internetowej. Obecnie mają JSON w następującym formacie:

[

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

Które analizują po wyjściu ze znaku \ za pomocą Javascript.

Mój problem polega na tym, że analizuję go w systemie iOS za pomocą następującego polecenia:

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

I zrób to:

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

Zamiast Array mam NSMutableString obiekt.

  • Strona jest już w produkcji, więc nie mogę poprosić ich o zmianę istniejącej struktury, aby zwrócić proper JSON object. To będzie dla nich dużo pracy.

  • Więc, dopóki nie zmienią podstawowej konstrukcji, czy jest jakiś sposób, żebym mógł to zrobić w iOS tak jak robią to z javascript na ich website?

Każda pomoc/sugestia byłaby dla mnie bardzo pomocna.

Author: svmrajesh, 2013-10-16

14 answers

Poprawny JSON powinien prawdopodobnie wyglądać tak:

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

Ale jeśli utkniesz w tym formacie podanym w twoim pytaniu, musisz zmienić słownik za pomocą NSJSONReadingMutableContainers, a następnie ponownie wywołać NSJSONSerialization dla każdego z tycharray wpisów:

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);
    }
}
 42
Author: Rob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-16 15:34:06

Wypróbuj tę prostą metodę....

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

}
 13
Author: svmrajesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-08 04:06:27

Jak ludzie przed chwilą powiedzieli powyżej, musisz najpierw użyć NSJSONSerialization, aby deserializować JSON w użyteczne struktury danych jako NSDictionary lub NSArray.

Jednakże, jeśli chcesz zmapować zawartość JSON do obiektów Objective-C, będziesz musiał zmapować każdy atrybut z NSDictionary/NSArray do właściwości object. Może to być trochę bolesne, jeśli twoje obiekty mają wiele atrybutów.

W celu automatyzacji procesu, polecam skorzystać z kategorii Motis na NSObject (osobisty projekt), aby go zrealizować, dzięki czemu jest bardzo lekki i elastyczny. Możesz przeczytać jak go używać w ten post . Aby to pokazać, wystarczy zdefiniować słownik z mapowaniem atrybutów obiektu JSON do nazw właściwości obiektu Objective-C w podklasach 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",
            };
}

A następnie wykonaj parsowanie wykonując:

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

Ustawienie właściwości ze słownika odbywa się za pomocą KeyValueCoding (KVC) i można zweryfikować każdy atrybut przed ustawienie go poprzez walidację KVC.

Mam nadzieję, że to pomoże Tobie tak samo, jak mnie.

 4
Author: vilanovi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-06-27 07:29:01
//-------------- 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);
}
 3
Author: ashvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-01 07:27:06

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

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-----------------------------------

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----------------------

[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----------------------

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

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

[tableview reloadData];
} ;
 3
Author: ashvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-01 08:29:50
  • Zawsze możesz odsunąć jsonData przed dostarczeniem go do NSJSONSerialization. Możesz też użyć ciągu got do skonstruowania innego json object, aby uzyskać array.

  • NSJSONSerialization czy robi dobrze, wartość w twoim przykładzie powinna być ciągiem znaków.

 2
Author: pinxue,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-14 03:56:35

Jak powiedziała inna odpowiedź, ta wartość jest ciągiem znaków.

Możesz obejść go, zamieniając ten łańcuch w dane, ponieważ wydaje się być prawidłowym łańcuchem json, a następnie przetworzyć ten obiekt danych JSON z powrotem do tablicy, którą możesz dodać do słownika jako wartość klucza.

 1
Author: Abizern,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-16 13:29:26
 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"];
 1
Author: abc,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-16 09:40:55
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);
    }
 1
Author: ashvin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-09 16:29:42

Może to ci pomoże.

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

    }

}
 1
Author: Nilesh Parmar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-21 09:27:34

JSON metoda domyślna:

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

Metoda powrotu:

+(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;
}
 0
Author: Arjun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-26 17:53:26

@ property NSMutableURLRequest * urlReq;

@ property NSURLSession * session;

@property NSURLSessionDataTask * dataTask;

@ property NSURLSessionConfiguration * sessionConfig;

@property NSMutableDictionary * appData;

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

  • (void) viewDidLoad { [super viewDidLoad]; siebie.valueArray = [[NSMutableArray alloc]init]; siebie.keysArray = [[NSMutableArray alloc]init]; siebie.linkString = @ " http://country.io/names.json "; [self getData];

- (void)getData
{ siebie.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];
 0
Author: teja,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-20 04:11:26
#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];
}
 0
Author: Mangi Reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-01 18:06:20
-(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

    }
 -1
Author: iAmita Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-21 11:57:31