gpt4 book ai didi

objective-c - 将 JSON 解析为对象

转载 作者:行者123 更新时间:2023-11-28 22:55:32 24 4
gpt4 key购买 nike

我要解析以下 JSON 文件:

[
{
"name": "kkkk",
"empid": "55628",
"address": "mumbai",
"mobile": "9528558"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "9689597"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "9689999597"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "9689999597"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "9689597"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "9689999597"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "9689999597"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "9689999597"
},
{
"name": "xtreme",
"empid": "20",
"address": "stripes",
"mobile": "96897"
},
{
"name": "vx",
"empid": "96",
"address": "addre",
"mobile": "9689999596"
},
{
"name": "vxx",
"empid": "96",
"address": "addre",
"mobile": "968999"
},
{
"name": "vx",
"empid": "96",
"address": "addre",
"mobile": "9699596"
},
{
"name": "vxertdrt",
"empid": "96",
"address": "addre",
"mobile": "968996"
},
{
"name": "vx",
"empid": "96",
"address": "addre",
"mobile": "999596"
}

]

我有以下解析代码:

 SBJSON *parser=[[SBJSON alloc]init];
array=[parser objectWithString:firstParseData];
NSString *secondParseData=[array objectAtIndex:0];
NSLog(@"name=%@",secondParseData);

通过这段代码,我得到以下字符串格式的输出:

 name={
address = mumbai;
empid = 55628;
mobile = 9525878558;
name = kkkk;

但我想要员工对象形式的输出。我怎样才能从 json 中创建员工对象??

最佳答案

您必须有一个带有构造函数的 Employee 类。然后你可以做这样的事情。您不需要创建 SBJson 解析器对象。您可以直接在 NSString 上使用它,这是 SBJson 的优点。

NSString * data = @"[
{
"name": "kkkk",
"empid": "55628",
"address": "mumbai",
"mobile": "9528558"
},
...
{
"name": "vx",
"empid": "96",
"address": "addre",
"mobile": "999596"
}
]";

// Get an array with all the employees inside
NSArray *myArray = [data JSONValue];

// Pick out the first employee
NSDictionary *firstEmployee = myArray[0];

// Create an object for him
Employee *firstEmployeeObject = [[Employee alloc] initWithAddress:[firstEmployee objectForKey:@"address"] andEmpID:[firstEmployee objectForKey:@"empid"] andMobile:[firstEmployee objectForKey:@"mobile"] andName:[firstEmployee objectForKey:@"name"]];

如果您不使用 ARC,请不要忘记释放您的对象。

关于objective-c - 将 JSON 解析为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10876218/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com