Search code examples
iosobjective-cnsjsonserialization

JSON Parsing Issue


Hello I am new to iOS development. I am trying to parse a JSON response. Below is the top part of the response:

Table =                     
{
  Rows = {
  results = (
            {
  Cells =    {
      results = (
              {
                Key = Rank;
                Value = "6.251145362854";
                ValueType = "Edm.Double";
                "__metadata" =  {
                                 type = "SP.KeyValue";
                                 };
                                },
              {
                Key = DocId;
                Value = 978473;
                ValueType = "Edm.Int64";
                 "__metadata" =                               
              {
                type = "SP.KeyValue";
              };
              },
              {
              Key = WorkId;
              Value = 978473;
              ValueType = "Edm.Int64";
              "__metadata" =  {
                               type = "SP.KeyValue";
                               };
              },
            {
             Key = Title;
             Value = "Vneea Ready!";
             ValueType = "Edm.String";
             "__metadata" =                                              
             {
                type = "SP.KeyValue";
              };
             },.........................

Now I am using

    NSError *error;
    NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSDictionary *results = jsonObject[@"Table"][@"Rows"][@"results"];

So I was able to refine it until here, but then I use

NSDictionary *results = jsonObject[@"Table"][@"Rows"][@"results"][@"Cells"];

When I am going further for Cells and results it is giving me Empty element Error, After referring to this post JSON parsing using NSJSONSerialization in iOS, it seems like "(" means an array in the response, but it is not working for me. Can someone help me, please?


Solution

  • results is an array, not a dictionary, so you cannot access its contents by name. Your JSON doesn't look well formed, though, because Key should be a string ("Title" not Title).

    Each element in the results array is a dictionary, so to get the Value that corresponds to Title you can use

    NSArray *results=jsonObject[@"Table"][@"Rows"][@"results"];
    NSDictionary *result=[results objectAtIndex:0];   // access the first result
    
    for (NSDictionary *result in results) {
       if ([result[@"Key"] isEqualToString:@"Title"]) {
          NSLog(@"The value of Title is %@",result[@"Value"]);
          break;
       }
    }