Domanda

Ho qualche problema con JSON Parsing.Quando ho colpito URL, ho JSON Risposta come questa:

//JSON 1
{ "data":
  {"array":
    ["3",
       {"array":
          [
            {"id":"1","message":"Hello","sender":"inot"},
            {"id":"2","message":"World","sender":"inot"},
            {"id":"3","message":"Hi","sender":"marza"}
          ]
        }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}
.

Ma se il risultato dei dati è solo 1, la risposta JSON è come questa:

//JSON 2
{ "data":
  {"array":
    ["3",
       {"array":
          {"id":"3","message":"Hi","sender":"marza"}
       }
     ]
   },
 "message":"MSG0001:Success",
 "status":"OK"
}
.

I Attuare questo codice per ottenere l'ID, il messaggio del messaggio e il valore del mittente e funzionare bene su JSON 1, ma errore su JSON 2. Io uso JSON-Framework.E la domanda è come rilevare che la risposta JSON è oggetto ({}) o array ([]) ??

// Parse the string into JSON
NSDictionary *json = [myString JSONValue];

// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
   NSLog(@"id      = %@",[item objectForKey:@"id"]);
   NSLog(@"message = %@",[item objectForKey:@"message"]);
   NSLog(@"sender  = %@",[item objectForKey:@"sender"]);
}
.

È stato utile?

Soluzione

È possibile utilizzare id e verificare se l'oggetto che ottieni è NSarray o NSDITICARIO come questo:

id item = [json valueForKeyPath:@"data.array"];
if ([item isKindOfClass:[NSArray class]]) {
    // item is an array
}
else if ([item isKindOfClass:[NSDictionary class]]) {
    // item is a dictionary
}
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top