gpt4 book ai didi

ios - 客户端服务器 json 响应

转载 作者:行者123 更新时间:2023-11-28 19:38:08 26 4
gpt4 key购买 nike

我需要在从网络获得响应后使用 post 方法显示键(货币)的特定对象。

#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.
}

我得到了响应 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"
}
]};

最佳答案

您的响应结构是:

-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 作为参数传递给它,并将所有此字典解析委托(delegate)给该方法。

此外,NSURLConnection自 iOS 9.0 起已弃用。你应该使用 NSURLSession反而。

关于ios - 客户端服务器 json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36831975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com