客户端服务器json响应

客户端服务器json响应

问题描述:

我需要在从web获得响应后,使用post方法显示键(货币)的特定对象。客户端服务器json响应

#import "ViewController.h" 

@interface ViewController() 
@end 

@implementation ViewController{ 

NSMutableData *mutableData; 
NSMutableString *arr; 

#define URL   @"website" 
// change this URL 
#define NO_CONNECTION @"No Connection" 
#define NO_VALUES  @"Please enter parameter values" 

} 



- (void)viewDidLoad { 
    [super viewDidLoad]; 

    // Do any additional setup after loading the view, typically from a nib. 
} 
-(IBAction)sendDataUsingPost:(id)sender{ 

    [self sendDataToServer :@"POST"]; 

} 

-(IBAction)sendDataUsingGet:(id)sender{ 

    [self sendDataToServer : @"GET"]; 
} 

-(void) sendDataToServer : (NSString *) method{ 
    NSString *[email protected]"3"; 
    serverResponse.text = @"Getting response from server..."; 
    NSURL *url = nil; 
    NSMutableURLRequest *request = nil; 
    if([method isEqualToString:@"GET"]){ 

     NSString *getURL = [NSString stringWithFormat:@"%@?branch_id=%@", URL, Branchid]; 
     url = [NSURL URLWithString: getURL]; 
     request = [NSMutableURLRequest requestWithURL:url]; 
     NSLog(@"%@",getURL); 

    }else{ // POST 

     NSString *parameter = [NSString stringWithFormat:@"branch_id=%@",Branchid]; 
     NSData *parameterData = [parameter dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]; 

     url = [NSURL URLWithString: URL]; 
     NSLog(@"%@", parameterData); 
     request = [NSMutableURLRequest requestWithURL:url]; 
     [request setHTTPBody:parameterData]; 

     arr= [NSMutableString stringWithUTF8String:[parameterData bytes]]; 

     NSLog(@"responseData: %@", arr); 
     //NSLog(@"%@",[[arr valueForKey:@"BranchByList"]objectForKey:@"currency"]); 



        } 

    [request setHTTPMethod:method]; 
    [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; 
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 
    //NSLog(@"%@",[connection valueForKeyPath:@"BranchByList.currency"]); 
    if(connection) 
    { 
     mutableData = [NSMutableData new]; 
     //NSLog(@"%@",[connection valueForKeyPath:@"BranchByList.currency"]); 

    } 
} 

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [mutableData setLength:0]; 
} 

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [mutableData appendData:data]; 
} 

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    serverResponse.text = NO_CONNECTION; 
    return; 
} 

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSMutableString *responseStringWithEncoded = [[NSMutableString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding]; 
    //NSLog(@"Response from Server : %@", responseStringWithEncoded); 
    NSLog(@"%@",responseStringWithEncoded ); 
    NSLog(@"%@",[responseStringWithEncoded valueForKeyPath:@"BranchByList.currency"]); 
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil]; 


    serverResponse.attributedText = attrStr; 
    // NSLog(@"%@",attrStr); 
} 



- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

我得到了回应branch_id = 3但我想显示为“货币”,但我尝试了很多,但失败。

这样我需要只显示货币.....从服务器 回应我的回应:

{"BranchByList": 
[ 
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newant‌​ara\/images\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24" 
}, 
{"id":"342","flag_image":"http:\/\/demo.techzarinfo.com\/newantara\/i‌​mages\/flags\/USD.png","units":"1","code":"USD B","currency":"US DOLLAR BIG","buy":"4.36","sell":"4.395","updated":"2016-04-11 03:24:24" 
} 
]}; 
+0

1.将您的代码缩小到相关片段,并为人们了解您的查询提供更多上下文。 2.为什么你使用'NSURLConnection'?它在9.0中被弃用。您现在应该使用'NSURLSession'现在 – NSNoob

+0

显示您的json响应您想要显示的内容 – 2016-04-25 04:27:05

+0

将此添加到您的问题的正文中。没有人会阅读此评论 – NSNoob

您回应结构为:

-Dictionary 
--Array 
---Dictionary Objects 

您需要将您的数据转换为NSDictionary解析它。

下面的代码为你做的:

NSError* error; 
NSDictionary* json = [NSJSONSerialization JSONObjectWithData: mutableData 
                options:kNilOptions 
                 error:&error]; //Now we got top level dictionary 

NSArray* responseArray = [json objectForKey:@"BranchByList"]; //Now we got mid level response array 


//Get Embeded objects from response Array: 

NSDictionary *priceDic = [responseArray objectAtIndex:0]; //Getting first object since you arent telling what the second object is for 

NSString *buyingPrice = [priceDic objectForKey: @"buy"]; //Buying price 
NSString *sellingPrice = [priceDic objectForKey:@"sell"]; //Selling price 

NSString *currency = [priceDic objectForKey:@"currency"]; //Currency 

虽然这仅仅是坚持点和完成工作。

完成工作的正确方法是创建响应的模型类。创建一个从NSObject继承的类,并将其用作此响应的模型。将initWithDic:方法添加到该类中,将它作为参数传递给响应dic,并将所有此字典解析委派给该方法。

此外,从iOS 9.0开始,NSURLConnection已被弃用。您应该改用NSURLSession

+1

非常感谢你所有的工作,现在..... –

尝试,这可能是它会帮助你: -

  NSString *str=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; 
      NSLog(@"str : %@",str); 

      NSDictionary *dict6 = [self cleanJsonToObject:responseData]; 
      NSLog(@"str : %@",dict6); 

     NSMArray *array1 = [dict6 objectForKey:@"BranchByList"]; 
     NSLog(@"DICT : %@",array1); 

NSDictionary *Dict3 = [array1 objectAtIndex:0]; 

    NSString *Str1 = [dict3 objectForKey:@"currency"]; 
    NSLog(@"Str1 : %@",Str1); 


     - (id)cleanJsonToObject:(id)data 
     { 
      NSError* error; 
      if (data == (id)[NSNull null]) 
      { 
       return [[NSObject alloc] init]; 
      } 
      id jsonObject; 
      if ([data isKindOfClass:[NSData class]]) 
      { 
       jsonObject = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]; 
      } else 
      { 
       jsonObject = data; 
      } 
      if ([jsonObject isKindOfClass:[NSArray class]]) 
      { 
       NSMutableArray *array = [jsonObject mutableCopy]; 
       for (int i = (int)array.count-1; i >= 0; i--) 
       { 
        id a = array[i]; 
        if (a == (id)[NSNull null]) 
        { 
         [array removeObjectAtIndex:i]; 
        } else 
        { 
         array[i] = [self cleanJsonToObject:a]; 
        } 
       } 
       return array; 
      } else if ([jsonObject isKindOfClass:[NSDictionary class]]) 
      { 
       NSMutableDictionary *dictionary = [jsonObject mutableCopy]; 
       for(NSString *key in [dictionary allKeys]) 
       { 
        id d = dictionary[key]; 
        if (d == (id)[NSNull null]) 
        { 
         dictionary[key] = @""; 
        } else 
        { 
         dictionary[key] = [self cleanJsonToObject:d]; 
        } 
       } 
       return dictionary; 
      } else 
      { 
       return jsonObject; 
      } 
     } 
+0

它不工作,它显示所有对象的价值.... –