簡體   English   中英

如何解析iOS中HTTP POST的JSON字符串輸出

[英]How can I parse the JSON string output from HTTP POST in iOS

我使用POST方法將一些參數發送到服務器,然后從那里得到響應並將其存儲在字符串“ serverResponse”中。這是我存儲在字符串中的服務器響應

{ 
    "carIdentifier":[
        {"carId":"91"},
        {"carId":"93"},
        {"carId":"114"},
        {"carId":"117"}
    ]
}

我有單獨的json解析代碼,但我不知道如何將此作為json解析代碼的輸入。 以下是我的json解析代碼

-(void)getcarList:(NSString *)serverResponse
{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSObject *recommendedcarJSON = nil;
        NSData *recommendedcarsData = [NSData dataWithContentsOfURL:[NSURL URLWithString:serverResponse]];
        NSLog(@"%@",recommendedcarsData);
        if(recommendedcarsData)
            recommendedcarJSON = [NSJSONSerialization JSONObjectWithData:recommendedBooksData options:NSJSONReadingMutableContainers error:nil];

        if(!recommendedcarsData){
            NSLog(@"Error with JSON Serialization");
        } else{
            [self saveRecommendedcarData:(NSDictionary *)recommendedcarJSON];
        }
    } );
}

在saveRecommendedcarData方法中,我正在創建一個plist並保存此解析的數據。 我如何給我的服務器響應字符串作為json解析的輸入?

NSError *jsonError = nil;
id allValues = [NSJSONSerialization JSONObjectWithData:[serverResponse dataUsingEncoding:NSUTF8StringEncoding]
                                               options:0
                                                 error:&jsonError];

if(jsonError!=nil)
    NSLog(@"Json_Err: %@",jsonError);

NSArray *carIdentifier = [(NSDictionary*)allValues objectForKey:@"carIdentifier"];
NSLog(@"%@",carIdentifier);

for(NSDictionary *dict in carIdentifier)
        NSLog(@"carId: %@",[dict valueForKey:@"carId"]);

嘗試這個。

UPDATE

-(void)getcarList:(NSString *)serverResponse
{

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        NSError *jsonError = nil;
        id allValues = [NSJSONSerialization JSONObjectWithData:[serverResponse dataUsingEncoding:NSUTF8StringEncoding]
                                                   options:0
                                                     error:&jsonError];

        if(jsonError!=nil)
            NSLog(@"Json_Err: %@",jsonError);

        NSArray *carIdentifier = [(NSDictionary*)allValues objectForKey:@"carIdentifier"];
        NSLog(@"%@",carIdentifier);

        for(NSDictionary *dict in carIdentifier)
                NSLog(@"carId: %@",[dict valueForKey:@"carId"]);

        } );
}

如果您想從日期中獲取價值,請使用以下代碼:

for(i=0 ; i < myDic.count; i++)
{
  NSLog(@"%@",[[myDic objectForKey:@"carIdentifier"] objectAtIndex:i] objectForKey:@"carId"])
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM