0

解析する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から従業員オブジェクトを作成するにはどうすればよいですか?

4

2 に答える 2

1

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

releaseARCを使用していない場合は、オブジェクトを忘れないでください。

于 2012-06-04T04:28:44.730 に答える
1

これを試して :

NSMutableArray *final_array =[[NSMutableArray alloc]init];
for (NSDictionary *dict in array) {
    Employee *obj =[[Employee alloc]init];
    for (id key in [dict allKeys]) {
        [obj setValue:[dict objectForKey:key] forKey:key];
    }
    [final_array addObject:obj];
}
于 2012-06-04T04:32:17.023 に答える