xcode 如何在iOS中将数据字符串转换为json对象和字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29383986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 06:54:29  来源:igfitidea点击:

How to convert data string to json object and string in iOS?

iosobjective-ciphonexcode

提问by Rajneesh

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

如何在 iOS 中将字符串转换为 JSON 对象或 JSON 数组?我的 JSON 字符串就像那样。

{"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.

我想从此字符串中获取 ID 或名称,如果现在有人请帮助我。

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

回答by Kalpesh

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

回答by Lalit Kumar

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

永远记住,当有 { } 大括号时,表示它是 Dictionary 而当 [ ] this 时,表示 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
}

回答by Retro

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.

这不是可以由 Objective c 解析的正确 JSON 字符串,从编码器获取字符串,您将获得一个有效字符串,除此之外,对于 JSON 到字典的转换在 iOS 中很简单,因为它本机支持。

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