Как я могу разобрать json-строку в nsdictionary?
Я пишу код для приложения для входа. может ли кто-нибудь помочь мне разобрать строку json?
мой код
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *loginDict = [parser objectWithString:loginDict error:nil];
[loginStatus release];
[connection release];
Ответы
Ответ 1
Пример данных:
NSString *strData = @"{\"1\": {\"name\": \"Jerry\",\"age\": \"12\"}, \"2\": {\"name\": \"Bob\",\"age\": \"16\"}}";
NSData *webData = [strData dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
NSLog(@"JSON DIct: %@", jsonDict);
Выход NSLog:
JSON DIct: {
1 = {
age = 12;
name = Jerry;
};
2 = {
age = 16;
name = Bob;
};
}
Ответ 2
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding]
NSLog([[loginStatus JSONValue] description],nil);
//This will give you parsed output.
Ответ 3
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSASCIIStringEncoding];
NSlog(@"json String is: %@",responseString);
NSDictionary *dictionary = [responseString JSONValue];
NSLog(@"Dictionary value is %@", [dictionary objectForKey:@"json"]);
результатом этого кода является: json String: { "json": { "Success": "Код активации." }}
После разговора результат: ------- Значение слова: { Success = "Код активации." };
Ответ 4
//*************Static Resopnse
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"demo" ofType:@"text"];
NSLog (@"Content: %@", filePath);
NSString *content = [[[NSString alloc] initWithContentsOfFile:filePath
usedEncoding:nil
error:nil] autorelease];
SBJSON *json = [[SBJSON new] autorelease];
NSString *str=[[NSString alloc]initWithString:content];
dictTemp = [json objectWithString:str error:nil];
NSLog(@"Actions is: %@",dictTemp);
NSArray *arr=[[dictTemp valueForKey:@"Data"] mutableCopy];
arrX=[[NSMutableArray alloc] init];
arrY=[[NSMutableArray alloc] init];
for(NSDictionary *dict in arr)
{
[arrX addObject:[dict valueForKey:@"Milestone"]];
[arrY addObject:[dict valueForKey:@"Sites"]];
}
NSLog(@"X is: %@",[arrX description]);
NSLog(@"Y is: %@",[arrY description]);