How to convert data string to json object and stri

2019-09-21 18:03发布

问题:

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

回答1:

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"]);
}


回答2:

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
}


回答3:

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