преобразовать в формат JSON в xcode 5

Я бы хотел подключить приложение для iPad к php. Мой код ниже:

 - (IBAction)loginbtn:(id)sender{
NSString *string1 =_text1.text;
NSString *string2 =_text2.text;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"myurl"]];
NSString *mystr=[NSString stringWithFormat:@"user1=%@,pwd=%@",string1,string2];
NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[mystr dataUsingEncoding:NSUTF8StringEncoding]];

NSURLConnection * conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

if (conn)
NSLog(@"Connection Successful");
else
NSLog(@"failed");

}

Вот как я могу преобразовать это в формат JSON, используя NSJsonSerialization, Может кто-нибудь мне помочь?

0

Решение

Используйте приведенные ниже методы для преобразования объекта в json строка и json строка для объекта.

+ (NSString *) getJSONString:(id)object {

NSString *jsonString = @"";
@try {
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:object
options:NSJSONWritingPrettyPrinted
error:&error];
if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
return jsonString;
}
@catch (NSException *exception) {
NSLog(@"Exception :%@",exception);
return jsonString;
}
}

//---------------------------------------------------------------

+ (id) getObjectFromJSONString:(NSString *)jsonString {
@try {
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
return object;
}
@catch (NSException *exception) {
NSLog(@"Exception :%@",exception);
return nil;
}
}
0

Другие решения

Взять объект NsmutableData как NSMutableData * webMerchantLoginAndProfileDataIphone;

В методе connectiondidfinishLoading вы получите следующие данные:

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

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

-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error
{
[delegate processMerchantLoginAndProfileData:@"error" success:0];

alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"You are not connected to the internet. Please check your internet connection and try again." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
[alert show];

return;
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
/Check the request and returns the response.
//NSLog(@"DONE. Received Bytes get iphone Data: %d", [webMerchantLoginAndProfileDataIphone length]);
theXMLMerchantLoginAndProfileDataIphone = [[NSString alloc]
initWithBytes: [webMerchantLoginAndProfileDataIphone mutableBytes]
length: [webMerchantLoginAndProfileDataIphone length]
encoding:NSUTF8StringEncoding];

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:theXMLMerchantLoginAndProfileDataIphone options:kNilOptions error:&error];

}
0

Прежде всего, вы должны добавить делегатов для NSURLConnection лайк <NSURLConnectionDelegate,NSURLConnectionDataDelegate> в противном случае ваш делегат не был бы вызван. мы будем принимать WebData как NSMutableData поэтому, когда вы получите ответ в данных, вы будете хранить эти данные в webData.

так в .час файл

@interface yourClass : UIViewController<NSURLConnectionDelegate,NSURLConnectionDataDelegate>
@property(nonatomic,strong)NSMutableData *webData;

Для реализации вам нужен метод 4 делегата, который связан с вашим NSURLConnection

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
strError = error.localizedDescription;
NSLog(@"Got Error from Server : %@",error.localizedDescription);
}
//this method will call once you get data from server so set your data length to 0.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.webData setLength:0];
}
//when receive data from server append that.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.webData appendData:data];
}
//once you get all data this method will be called that your connection is finish.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//    NSLog(@"HTTP RES :\n %@",[[NSString alloc]initWithData:self.webData encoding:NSUTF8StringEncoding]);

//check that you get response is in correct format like dictionary or array.
NSError *err;
id objectChecker = [NSJSONSerialization JSONObjectWithData:self.webData options:NSJSONReadingMutableContainers error:&err];

if ([objectChecker isKindOfClass:[NSArray class]])
{
//your response is array.
}
else if([objectChecker isKindOfClass:[NSDictionary class]])
{
//your response is dictionary.
}
else
{

}
}

Может быть, это поможет вам.

0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector