0

FINAL EDIT WITH SOLUTION:

The code for resolve the problem:

-(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:&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'
}
 }

NEW EDIT: My new code, nad the app crashes, sorry...

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);


NSData *jsondata = [content dataUsingEncoding:NSUTF8StringEncoding];

NSError *e = nil;
//NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsondata options: NSJSONReadingMutableContainers

error: &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);
}}

The log:

2014-02-14 12:09:50.649 appAbogados[34863:f803] 1 2014-02-14 12:09:50.651 appAbogados[34863:f803] Administrador 2014-02-14 12:09:50.685 appAbogados[34863:f803] its an array! 2014-02-14 12:09:50.686 appAbogados[34863:f803] jsonArray - ( { 0 = 1; 1 = 24898; 10 = "Espa\U00f1a"; 11 = ""; 12 = Administrador; 13 = 1; 14 = 0; 15 = ""; 16 = 00; 17 = ""; 18 = ""; 19 = 0000000001; 2 = "JOAN LLUIS GONZALEZ FERRERI"; 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 = "Nov 10 2011 11:32:54:000AM"; 39 = "\U00bd"; 4 = ""; 5 = ""; 6 = "juanluis@ferreriabogados.com"; 7 = ""; 8 = ""; 9 = ""; "Avis_Guardia" = 1; "Avis_Vista" = 0; CanalHabitualAbogado = 00; CertNombre = ""; ClienteSerieTurnoOficio = 00; ClienteTurnoOficio = 0000000001; CodigoAbogado = 1; CodigoColegioAbogado = 0; CodigoPostal = ""; Desc1 = 0; Desc2 = 0; Desc3 = 0; Desc4 = 0; Desc5 = 0; Desc6 = 0; Direccion = ""; ESPECIAL = "\U00bd"; EmpresaPredeterminadaEosCodigo = ""; EmpresaPredeterminadaEosNombre = ""; IPF = 0; IdOutLook = 000000002EEFA536C0B8B44B9B44E513587FBA9BA4F22000; ImportIdentificacion = ""; Mail = "juanluis@ferreriabogados.com"; MostrarInforme = 1; NIF = ""; Nombre = "JOAN LLUIS GONZALEZ FERRERI"; NombreColegioAbogado = ""; NombreComun = ""; Notas = ""; NumeroColegiado = 24898; Pais = "Espa\U00f1a"; Poblacion = ""; Provincia = ""; SerialCertificado = 1; Sexo = " "; "Tiempo_Avis" = 1; "Tiempo_Tipo" = 3; TipoVia = ""; UltimaModificacion = "Nov 10 2011 11:32:54:000AM"; Usuario = Administrador; } )


i have an script in php that response data in JSON.

When i receive the data, i have a string with the content, but i want to store these data in a dictionary because i want to access some values.

I have been trying to use NSJSONSerialization but my app crash everywhere. Im new and i have not idea please help.

My code is:

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);

The content of the variable "content" is:

2014-02-14 10:48:17.996 appAbogados[34082:f803] Contenido de content:

[{"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"}]

The response of PHP script:

[{"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"}]

Thanks very much.

Eladar
  • 151
  • 1
  • 8
  • NSString *content = [NSString stringWithUTF8String:[returnData bytes]]; NSData *jsondata = [content dataUsingEncoding:NSUTF8StringEncoding]; This is completely pointless. You convert NSData to an NSString to NSData. All you do is wasting time and memory (plus the possibility that someone sent UTF-16). – gnasher729 Feb 15 '15 at 16:50

4 Answers4

2

See srik's answer, you'll find the way to cast a json string to an array or dictionary.

How to use NSJSONSerialization

Also, post your code of using NSJSonSerialization and errors !

Regards,

Community
  • 1
  • 1
Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
  • I edit the post, i get this error: 2014-02-14 11:06:20.391 appAbogados[34221:f803] Error parsing JSON: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x686fb90 {NSDebugDescription=Garbage at end.} – Eladar Feb 14 '14 at 10:09
  • The error shows that there maybe an invalid character in your json string. I've copied your json and paste in a file, there're somes newline characters. I've deleted theses newline characters and use your code, it works. – Duyen-Hoa Feb 14 '14 at 10:23
  • in fact, your json string root is an dictionary, not array! -> sorry, we can consider as an array. However, I found in your json 'array', there are some dictionary that does not have value for key. for example "TipoVia":"" . When we cast json to an array of dictionary, this case is not accepted and the this item in array is not a dictionary!. – Duyen-Hoa Feb 14 '14 at 10:37
  • can u send me the code? sergio.upct@gmail.com – Eladar Feb 14 '14 at 10:39
  • I've added a code (it's your code). Run this code, application will crash at "TipoVia":"". Remove the 'count: %d' to avoid crash – Duyen-Hoa Feb 14 '14 at 10:47
2

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'
}
Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
  • That works, I LOVE U SO MUCH MAN, my green vote for u. Thanks for dedication with a noob like me. – Eladar Feb 14 '14 at 11:22
0

Try this:

Original:

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];

Edit: Since response is in square brackets:

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];
}
David P
  • 617
  • 1
  • 15
  • 26
  • Hmm, try without converting to stringValue; SO NSString *stringValue = [dict objectForKey:@"CodigoAbogado"]; – David P Feb 14 '14 at 10:19
  • I used ur code but none appear, the code doenst go into the if – Eladar Feb 14 '14 at 10:20
  • I used this: if ([object isKindOfClass:[NSArray class]]) { NSLog (@"Class array"); } then the app print "Class array" – Eladar Feb 14 '14 at 10:24
  • Okay I edited answer, how does that work? – David P Feb 14 '14 at 10:31
  • The app crash with this code -.- – Eladar Feb 14 '14 at 10:40
  • Where at, what does it say? Have you tried using the delegate method (and putting my code in there): `-(void)connection:(NSURLConnection *)connection didReceiveData(NSData *)data` – David P Feb 14 '14 at 10:42
  • Also why is the response encapsulated in array brackets []. Why not just curly brackets {} so the data goes straight into a dictionary. – David P Feb 14 '14 at 10:45
  • the code will crash at "[[dict objectForKey:@"CodigoAbogado"] stringValue];" cause in the array, there some object is not a dictionary, so the app may crash with error like xxxx does not respond to 'objectForKey:' – Duyen-Hoa Feb 14 '14 at 10:53
  • I was using that as an example, try using another key from your results (and also remove stringValue function too if it doesn't work). – David P Feb 14 '14 at 10:55
  • Are there any spaces in your response string? – David P Feb 14 '14 at 11:12
0
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);
    }
}

and edited json string in json.txt:

{"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":"Nov10 2011 11:32:54:000AM","UltimaModificacion":"Nov 10 2011 11:32:54:000AM","39":"\u00bd","ESPECIAL":"\u00bd"}

Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
  • I edited the first post, see that, the problem now is how to access the data. I want to get CodigoAbogado and Nombre of the array searching for key value and not like a Index – Eladar Feb 14 '14 at 10:55
  • You can convert to NSDictionary. Use the code of srik's, it converts to dictionary, not array. In that dictionary, it contains less items than your json string cause some item does not value. Then you can use [dict objectForKey:'CodigoAbogado'] to get its value. – Duyen-Hoa Feb 14 '14 at 10:58
  • I used the code of sriks but how the log says, keep being an array and not dictionary – Eladar Feb 14 '14 at 11:11