如何将 NSString 从 JSON 转换为 NSDictionary? [关闭]
Posted
技术标签:
【中文标题】如何将 NSString 从 JSON 转换为 NSDictionary? [关闭]【英文标题】:How convert a NSString from JSON to NSDictionary? [closed] 【发布时间】:2014-02-14 09:56:18 【问题描述】:最终编辑解决方案:
解决问题的代码:
-(void) atacarAbogados
abogados = [[[NSArray alloc] init] autorelease]; NSLog(@"%@", userReceived); NSString *myRequestString = [NSString stringWithFormat:@"user=%@", userReceived]; NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL
URLWithString:@""]];
[request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; [request setHTTPBody:myRequestData]; NSURLResponse *response; NSError *error; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response
错误:&error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]]; //NSLog(@"Contenido de content: %@", content); NSData *jsondata = [content dataUsingEncoding:NSUTF8StringEncoding]; NSError *jsonError = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsondata options:kNilOptions error:&jsonError]; if ([jsonObject isKindOfClass:[NSArray class]]) NSLog(@"its an array!"); NSArray *jsonArray = (NSArray *)jsonObject; for (id item in jsonArray) if ([item isKindOfClass:[NSDictionary class]]) NSString *foundValue = [(NSDictionary*)item objectForKey:@"CodigoAbogado"]; if (foundValue) NSLog(@"found 'CodigoAbogado' value: %@",foundValue); else NSLog(@"item %@ is not a dictionary",item); //do the same thing for another search key else NSLog(@"its probably a dictionary"); NSDictionary *jsonDictionary = (NSDictionary *)jsonObject; NSString *foundValue = [jsonDictionary objectForKey:@"CodigoAbogado "]; NSLog(@"found 'CodigoAbogado' value %@", foundValue); //it return null if not found value for key 'COdigoabogado'
新编辑: 我的新代码,应用程序崩溃了,抱歉...
NSLog(@"%@", userReceived); NSString *myRequestString = [NSString stringWithFormat:@"user=%@", userReceived]; NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]]; NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL
URLWithString:@""]];
[request setHTTPMethod:@"POST"]; [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"]; [request setHTTPBody:myRequestData]; NSURLResponse *response; NSError *error; NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response
错误:&error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]]; //NSLog(@"Contenido de content: %@", content); NSData *jsondata = [content dataUsingEncoding:NSUTF8StringEncoding]; NSError *e = nil; //NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsondata options: NSJSONReadingMutableContainers
错误:&e];
NSError *jsonError = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsondata options:kNilOptions error:&jsonError]; if ([jsonObject isKindOfClass:[NSArray class]]) NSLog(@"its an array!"); NSArray *jsonArray = (NSArray *)jsonObject; NSLog(@"jsonArray - %@",jsonArray); else NSLog(@"its probably a dictionary"); NSDictionary *jsonDictionary = (NSDictionary *)jsonObject; NSLog(@"jsonDictionary - %@",jsonDictionary);
日志:
2014-02-14 12:09:50.649 appAbogados[34863:f803] 1 2014-02-14 12:09:50.651 appAbogados[34863:f803] 管理员 2014-02-14 12:09:50.685 appAbogados[34863:f803] 它是一个数组! 2014-02-14 12:09:50.686 appAbogados[34863:f803] jsonArray - ( 0 = 1; 1 = 24898; 10 = "西班牙\U00f1a"; 11 = ""; 12 = 管理员; 13 = 1; 14 = 0; 15 = ""; 16 = 00; 17 = ""; 18 = ""; 19 = 0000000001; 2 =“琼·路易斯·冈萨雷斯·费雷里”; 20 = 00; 21 = 0; 22 = ""; 23 = ""; 24 = ""; 25 = " "; 26 = 0; 27 = 0; 28 = 0; 29 = 0; 3 = ""; 30 = 0; 31 = 0; 32 = 1; 33 = 0; 34 = 1; 35 = 3; 36 = 1; 37 = 000000002EEFA536C0B8B44B9B44E513587FBA9BA4F22000; 38 =“2011 年 11 月 10 日上午 11:32:54:000”; 39 = "\U00bd"; 4 = ""; 5 = ""; 6 =“juanluis@ferreriabogados.com”; 7 = ""; 8 = ""; 9 = ""; “Avis_Guardia” = 1; “Avis_Vista”= 0; CanalHabitualAbogado = 00; 证书编号 = ""; ClienteSerieTurnoOficio = 00; ClienteTurnoOficio = 0000000001; CodigoAbogado = 1; CodigoColegioAbogado = 0; CodigoPostal = ""; 描述1 = 0; Desc2 = 0; Desc3 = 0; Desc4 = 0; Desc5 = 0; Desc6 = 0; 方向 = ""; 特别 = "\U00bd"; EmpresaPredeterminadaEosCodigo = ""; EmpresaPredeterminadaEosNombre = ""; IPF = 0; IdOutLook = 000000002EEFA536C0B8B44B9B44E513587FBA9BA4F22000; 进口标识 = ""; 邮件=“juanluis@ferreriabogados.com”; MostrarInforme = 1; NIF = ""; Nombre = "琼·路易斯·冈萨雷斯·费雷里"; NombreColegioAbogado = ""; NombreComun = ""; 注释 = ""; NumeroColegiado = 24898; Pais = "Espa\U00f1a"; Poblacion = ""; 省 = ""; SerialCertificado = 1; 性=“”; "Tiempo_Avis" = 1; "Tiempo_Tipo" = 3; TipoVia = ""; UltimaModificacion = "2011 年 11 月 10 日上午 11:32:54:000"; Usuario = 管理员; )
我在 php 中有一个脚本,它以 JSON 格式响应数据。
当我收到数据时,我有一个包含内容的字符串,但我想将这些数据存储在字典中,因为我想访问一些值。
我一直在尝试使用 NSJSONSerialization,但我的应用程序到处崩溃。我是新手,我不知道请帮忙。
我的代码是:
NSLog(@"%@", userReceived);
NSString *myRequestString = [NSString stringWithFormat:@"user=%@", userReceived];
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@""]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
[request setHTTPBody:myRequestData];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSLog(@"Contenido de content: %@", content);
变量“content”的内容是:
2014-02-14 10:48:17.996 appAbogados[34082:f803] 内容内容:
["0":"1","CodigoAbogado":"1","1":"24898","NumeroColegiado":"24898","2":"JOAN LLUIS GONZALEZ FERRERI","Nombre":"JOAN LLUIS GONZALEZ
FERRERI","3":"","NombreComun":"","4":"","NIF":"","5":"","Direccion":"","6":"juanluis@ferreriabogados.com","Mail":"juanluis@ferreriabogados.com","7":"","CodigoPostal":"","8":"","Poblacion":"","9":"","Provincia":"","10":"Espa\u00f1a","Pais":"Espa\u00f1a","11":"","Notas":"","12":"Administrador","Usuario":"Administrador","13":"1","SerialCertificado":"1","14":0,"CodigoColegioAbogado":0,"15":"","NombreColegioAbogado":"","16":"00","CanalHabitualAbogado":"00","17":"","EmpresaPredeterminadaEosCodigo":"","18":"","EmpresaPredeterminadaEosNombre":"","19":"0000000001","ClienteTurnoOficio":"0000000001","20":"00","ClienteSerieTurnoOficio":"00","21":0,"IPF":0,"22":"","TipoVia":"","23":"","ImportIdentificacion":"","24":"","CertNombre":"","25":"
","Sexo":"
","26":0,"Desc1":0,"27":0,"Desc2":0,"28":0,"Desc3":0,"29":0,"Desc4":0,"30":0,"Desc5":0,"31":0,"Desc6":0,"32":1,"Avis_Guardia":1,"33":0,"Avis_Vista":0,"34":1,"Tiempo_Avis":1,"35":3,"Tiempo_Tipo":3,"36":1,"MostrarInforme":1,"37":"000000002EEFA536C0B8B44B9B44E513587FBA9BA4F22000","IdOutLook":"000000002EEFA536C0B8B44B9B44E513587FBA9BA4F22000","38":"Nov
10 2011 11:32:54:000AM","UltimaModificacion":"Nov 10 2011
11:32:54:000AM","39":"\u00bd","ESPECIAL":"\u00bd"]
PHP脚本的响应:
["0":"1","CodigoAbogado":"1","1":"24898","NumeroColegiado":"24898","2":"JOAN LLUIS GONZALEZ FERRERI","Nombre":"JOAN LLUIS GONZALEZ
FERRERI","3":"","NombreComun":"","4":"","NIF":"","5":"","Direccion":"","6":"juanluis@ferreriabogados.com","Mail":"juanluis@ferreriabogados.com","7":"","CodigoPostal":"","8":"","Poblacion":"","9":"","Provincia":"","10":"Espa\u00f1a","Pais":"Espa\u00f1a","11":"","Notas":"","12":"Administrador","Usuario":"Administrador","13":"1","SerialCertificado":"1","14":0,"CodigoColegioAbogado":0,"15":"","NombreColegioAbogado":"","16":"00","CanalHabitualAbogado":"00","17":"","EmpresaPredeterminadaEosCodigo":"","18":"","EmpresaPredeterminadaEosNombre":"","19":"0000000001","ClienteTurnoOficio":"0000000001","20":"00","ClienteSerieTurnoOficio":"00","21":0,"IPF":0,"22":"","TipoVia":"","23":"","ImportIdentificacion":"","24":"","CertNombre":"","25":"
","Sexo":"
","26":0,"Desc1":0,"27":0,"Desc2":0,"28":0,"Desc3":0,"29":0,"Desc4":0,"30":0,"Desc5":0,"31":0,"Desc6":0,"32":1,"Avis_Guardia":1,"33":0,"Avis_Vista":0,"34":1,"Tiempo_Avis":1,"35":3,"Tiempo_Tipo":3,"36":1,"MostrarInforme":1,"37":"000000002EEFA536C0B8B44B9B44E513587FBA9BA4F22000","IdOutLook":"000000002EEFA536C0B8B44B9B44E513587FBA9BA4F22000","38":"Nov
10 2011 11:32:54:000AM","UltimaModificacion":"Nov 10 2011
11:32:54:000AM","39":"\u00bd","ESPECIAL":"\u00bd"]
非常感谢。
【问题讨论】:
NSString *content = [NSString stringWithUTF8String:[returnData bytes]]; NSData *jsondata = [内容 dataUsingEncoding:NSUTF8StringEncoding];这是完全没有意义的。您将 NSData 转换为 NSString 到 NSData。您所做的只是浪费时间和内存(加上有人发送 UTF-16 的可能性)。 【参考方案1】:NSError *jsonError = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsondata options:kNilOptions error:&jsonError];
if ([jsonObject isKindOfClass:[NSArray class]])
NSLog(@"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
for (id item in jsonArray)
if ([item isKindOfClass:[NSDictionary class]])
NSString *foundValue = [(NSDictionary*)item objectForKey:@"CodigoAbogado"];
if (foundValue)
NSLog(@"found 'CodigoAbogado' value: %@",foundValue);
else
NSLog(@"item %@ is not a dictionary",item);
//do the same thing for another search key
else
NSLog(@"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSString *foundValue = [jsonDictionary objectForKey:@"CodigoAbogado "];
NSLog(@"found 'CodigoAbogado' value %@", foundValue); //it return null if not found value for key 'COdigoabogado'
【讨论】:
那行得通,我非常爱你,我对你投了绿票。感谢像我这样的菜鸟的奉献。【参考方案2】:查看 srik 的回答,您会找到将 json 字符串转换为数组或字典的方法。
How to use NSJSONSerialization
另外,发布您使用 NSJSonSerialization 和错误的代码!
问候,
【讨论】:
我编辑帖子,我收到此错误:2014-02-14 11:06:20.391 appAbogados[34221:f803] 解析 JSON 时出错:错误域 = NSCocoaErrorDomain 代码 = 3840 “操作无法” t 完成。(Cocoa 错误 3840。)“(垃圾结束。) UserInfo=0x686fb90 NSDebugDescription=垃圾结束。 该错误表明您的json字符串中可能存在无效字符。我已经复制了你的 json 并粘贴到一个文件中,有一些换行符。我已经删除了这些换行符并使用了你的代码,它可以工作。 其实你的json字符串根是字典,不是数组! -> 抱歉,我们可以将其视为一个数组。但是,我在您的 json 'array' 中发现,有些字典没有键值。例如 "TipoVia":"" 。当我们将 json 转换为字典数组时,不接受这种情况,并且数组中的该项不是字典!。 你能把代码发给我吗? sergio.upct@gmail.com 我添加了一个代码(这是你的代码)。运行此代码,应用程序将在“TipoVia”:“”处崩溃。删除“计数:%d”以避免崩溃【参考方案3】:NSString *jsonString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"json" ofType:@"txt"] encoding:NSUTF8StringEncoding error:nil];
NSData *jsondata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsondata options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray)
NSLog(@"Error parsing JSON: %@", e);
else
for(NSDictionary *item in jsonArray)
NSLog(@"Item: %@, count: %d", item, item.allKeys.count);
并在 json.txt 中编辑了 json 字符串:
"0":"1","CodigoAbogado":"1","1":"24898","NumeroColegiado":"24898","2":"JOAN LLUIS GONZALEZ FERRERI","Nombre" :"JOAN LLUIS GONZALEZ FERRERI","3":"","NombreComun":"","4":"","NIF":"","5":"","Direccion":"", "6":"juanluis@ferreriabogados.com","邮件":"juanluis@ferreriabogados.com","7":"","CodigoPostal":"","8":"","Poblacion":" ","9":"","Provincia":"","10":"Espa\u00f1a","Pais":"Espa\u00f1a","11":"","Notas":"", "12":"管理员","Usuario":"管理员","13":"1","SerialCertificado":"1","14":0,"CodigoColegioAbogado":0,"15":"" ,"NombreColegioAbogado":"","16":"00","CanalHabitualAbogado":"00","17":"","EmpresaPredeterminadaEosCodigo":"","18":"","EmpresaPredeterminadaEosNombre":" ","19":"0000000001","ClienteTurnoOficio":"0000000001","20":"00","ClienteSerieTurnoOficio":"00","21":0,"IPF":0,"22": "","TipoVia":"","23":"","ImportIdentificacion":"","24":"","CertNombre":"","25":"","Sexo":" ","26":0,"Desc1":0,"27":0,"Desc2":0,"28":0,"Desc3":0,"29":0,"Desc4":0, "30":0,"Desc5":0,"31":0,"Desc6":0,"32":1,"Avis_Gu ardia":1,"33":0,"Avis_Vista":0,"34":1,"Tiempo_Avis":1,"35":3,"Tiempo_Tipo":3,"36":1,"MostrarInforme" :1,“37”:“000000002EEFA536C0B8B44B9B44E513587B444E513587FB444F22000”“IDOUTLOOK”:“000000002EEFA536C0B8B44B9B444E513587FB444E513587FB444E513587FB444E513587FB444E513587FB444E513587FB444E513587FBA9BA4F22000”:2011年11月11:32:54:000AM“,”Ultimamodificion“:”2011年11月10日11:32:54:000AM ","39":"\u00bd","ESPECIAL":"\u00bd"
【讨论】:
我编辑了第一篇文章,看到了,现在的问题是如何访问数据。我想获取数组的 CodigoAbogado 和 Nombre 来搜索键值,而不是像索引 您可以转换为 NSDictionary。使用 srik 的代码,它转换为字典,而不是数组。在该字典中,它包含的项目少于您的 json 字符串,因为某些项目没有价值。然后你可以使用 [dict objectForKey:'CodigoAbogado'] 来获取它的值。 我使用了 sriks 的代码,但是日志怎么说,保持数组而不是字典【参考方案4】:试试这个:
原文:
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
if([object isKindOfClass:[NSDictionary class]])
NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:object];
NSString *stringValue = [[dict objectForKey:@"CodigoAbogado"] stringValue];
编辑:由于响应在方括号中:
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:returnData options:kNilOptions error:&error];
if([object isKindOfClass:[NSArray class]])
NSArray *array = [[NSArray alloc] initWithArray:object];
for(NSDictionary *dict in array)
NSString *stringValue = [[dict objectForKey:@"CodigoAbogado"] stringValue];
【讨论】:
嗯,不要转换成stringValue试试; SO NSString *stringValue = [dict objectForKey:@"CodigoAbogado"]; 我使用了你的代码,但没有出现,代码没有进入 if 我用过这个: if ([object isKindOfClass:[NSArray class]]) NSLog (@"Class array"); 然后应用程序打印“类数组” 好的,我编辑了答案,它是如何工作的? 应用程序因此代码而崩溃-.-以上是关于如何将 NSString 从 JSON 转换为 NSDictionary? [关闭]的主要内容,如果未能解决你的问题,请参考以下文章
将 JSON 数据从 NSData 转换为 NSDictionary
如果将一个NSObject从NSDictionary转换为NSString?
将 JSON 数据的 NSString 转换为 NSArray [关闭]
如何将 NSString 从 CamelCase 转换为 TitleCase,将“playerName”转换为“Player Name”?