-2

How to convert string to JSON object or JSON array in iOS? my JSON string Like That.

{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}

I want to get ID or Name from this string please help me if anyone now this.

Thank You.

I try below code but print null

  NSString *JsonString=@"{"Data": [{"ID":"1","Name":"Raj"},{"ID":"2","Name":"Rajneesh"}]}";
    NSData *objectData = [JsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData options:0 error:&error];
    NSArray* array = [json objectForKey:@"Data"];
    NSLog(@"Print Array %@",array);
6

3 Answers 3

5

Use this

NSString *str=@"{\"Data\": [{\"ID\":\"1\",\"Name\":\"Raj\"},{\"ID\":\"2\",\"Name\":\"Rajneesh\"}]}";

NSMutableDictionary *dict=[NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:nil];

NSMutableArray *dataArr=[dict valueForKey:@"Data"];
for (NSDictionary *userData in dataArr) {
    NSLog(@"Id:%@ Name:%@",[userData valueForKey:@"ID"],[userData valueForKey:@"Name"]);
}
Sign up to request clarification or add additional context in comments.

Comments

1

Always Remember that when there are { } curly brackets, it means it is Dictionary and when [ ] this, means Array

NSURL *url=[NSURL URLWithString:@"Your JSON URL"];

NSData *data = [[NSData alloc] initWithContentsOfURL:url];

NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

NSArray *array = json[@"Data"];

for(NSMutableDictionary *dic in array)
{
  NSLog(@"%@",dic[@"ID"]); // give 1 & 2
  NSLog(@"%@",dic[@"Name"]); // Raj and Rajneesh
}

Comments

0

This is not the correct JSON string which can be parsed by Objective c, get string from encoder and you will get a valid string, other then that for JSON to Dictionary conversion is simple in iOS as its natively supported.

NSData *data = [strJSON dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
                                                             options:kNilOptions
                                                               error:&error]; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.