Como detectar um objeto JSON/JSON Matriz no XCode usando JSON-Quadro
-
17-09-2020 - |
Pergunta
Eu tenho algum problema com JSON análise.Quando eu bati o URL, eu tenho uma resposta JSON como:
//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"
}
Mas se o resultado dos dados é de apenas 1, a resposta JSON é como este:
//JSON 2
{ "data":
{"array":
["3",
{"array":
{"id":"3","message":"Hi","sender":"marza"}
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
Eu implementar este código para obter o id de mensagem e o remetente valor, e funcionar bem em JSON 1, mas o erro em JSON 2.Eu uso JSON-Quadro.E a questão é como detectar que a resposta JSON é objeto ({ }) ou matriz ([ ]) ??
// 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"]);
}
Solução
Você pode usar id
e verificar se o objeto que você recebe é NSArray ou NSDictionary como este:
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
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow