我在控制台中有以下json值:
{"TokenID":"kuiHigen21","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky@itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
这是我的服务器api:@“http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login” // api需要5个参数。 当我将数据发布到服务器api时,值被发布到服务器,我得到了json格式的上述响应。
我想解析上面在响应中得到的JSON值并保存在sqlite数据库中。
我正在使用此代码来解析上面的JSON值:
-(void)connectionDidFinishLoadingNSURLConnection *)connection
{
NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] lengthwebData length] encoding:NSUTF8StringEncoding];
NSLog(@"%@",loginStatus);
self.webData = nil;
SBJSON *parser =[[SBJSON alloc]init];
NSURLRequest *request = [NSURLRequest requestWithURLNSURL URLWithString"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login.json"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
//NSDictionary *object = [parser objectWithString:json_string error:nil];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(@"%@ - %@", [status objectForKey"Login"],[status objectForKey"LoginKey"]);
[connection release]; [webData release];
}
答案 0 :(得分:1)
你应该查看一些JSON解析器,我个人最喜欢的是json-framework。在项目中包含其中一个之后,您从服务器获得了JSON响应:
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *statuses = [result objectForKey:@"Result"];
将返回结果数组(数组中的每个对象都是NSDictionary)。
答案 1 :(得分:0)
您可以借助模型类Result
将其保存到数据库中NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *result = [json_string JSONValue];
NSArray *values = [result objectForKey:@"Result"];
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int index = 0; index<[values count]; index++) {
NSMutableDictionary * value = [values objectAtIndex:index];
Result * result = [[Result alloc] init];
result.UserId = [value objectForKey:@"UserId"];
result. FirstName = [value objectForKey:@"FirstName"];
...
[results addObject:result];
[result release];
}
使用结果数组将其保存到数据库中。
for (int index = 0; index<[results count]; index++) {
Result * result = [results objectAtIndex:index];
//save the object variables to database here
}