客户端服务器json响应

时间:2016-04-25 04:21:42

标签: ios objective-c iphone json

我需要在收到网络回复后使用post方法显示密钥(货币)的特定对象。

long l = 5

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

我的回答是这样的,我只需要显示货币......  来自服务器的响应:

#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 *Branchid=@"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.
}

2 个答案:

答案 0 :(得分:3)

您的回复结构是:

-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:方法,将您的响应传递给参数,并将所有这些字典解析委托给该方法。

此外,自iOS 9.0起不推荐使用NSURLConnection。您应该使用NSURLSession代替。

答案 1 :(得分:0)

试试这可能会对你有帮助: -

         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;
            }
        }