Mujtaba Mujtaba - 5 months ago 9
Objective-C Question

How to parse NSDictionary

I want to parse like this dictionary

{
text = "[{\"UserId\":0,\"UserCode\":\"abc\",\"Password\":[31,0,221,51,21,211,31,38,231,41,121,221,171,201,11,201,21,201,181,51],\"SaltValue\":[],\"RoleId\":1,\"Salutation\":\"\",\"FirstName\":\"abc\",\"LastName\":\"xyz\",\"EmailId\":\"abc@gmail.com\",\"MobilNo\":\"9876543210\",\"Status\":true,\"AccesType\":1,\"AccessDivIds\":\"1,\",\"SuperiorId\":0,\"RepName\":\"Self\",\"AccessLevel\":1,\"BranchAccessType\":1,\"AccessBranchIds\":\"\",\"SPAccessType\":2,\"AccessSPIds\":\"\",\"IsGlobalUser\":true,\"IPAddresses\":null,\"FPAccessType\":1,\"RoleName\":\"Admin\",\"EmpId\":100,\"EmpName\":\"abc\"}]";
}


How to parse UserCode value in label when there is dictionary like this. Thanks in advance.

Answer

If this is your dictionary that you are getting in response:

NSDictionary *dic = @{
                          @"text":@"[{\"UserId\":0,\"UserCode\":\"abc\",\"Password\":[31,0,221,51,21,211,31,38,231,41,121,221,171,201,11,201,21,201,181,51],\"SaltValue\":[],\"RoleId\":1,\"Salutation\":\"\",\"FirstName\":\"abc\",\"LastName\":\"xyz\",\"EmailId\":\"abc@gmail.com\",\"MobilNo\":\"9876543210\",\"Status\":true,\"AccesType\":1,\"AccessDivIds\":\"1,\",\"SuperiorId\":0,\"RepName\":\"Self\",\"AccessLevel\":1,\"BranchAccessType\":1,\"AccessBranchIds\":\"\",\"SPAccessType\":2,\"AccessSPIds\":\"\",\"IsGlobalUser\":true,\"IPAddresses\":null,\"FPAccessType\":1,\"RoleName\":\"Admin\",\"EmpId\":100,\"EmpName\":\"abc\"}]"
                          };

then first get that "text" value and parse that string for json decode.

    NSString *string = [dic valueForKey:@"text"];

    NSData *data =[string dataUsingEncoding:NSUTF8StringEncoding];

    NSError* error;

Here you will get array of objects which are {} in this given "text" string.

    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSUTF8StringEncoding error:&error];

After getting array you can do loop to get all users usercode; Here you can get only first user's code.

    NSDictionary *firstObj = [array objectAtIndex:0];

    NSString *UserCode = [firstObj valueForKey:@"UserCode"];

Hope this might help you:)