Hi, I know barely nothing about JSON and I need to send a request to a server and read the data coming from it, using the iPhone only.
I have tried to use the jason-framework to do that, but after readin the documentations I was not able to figure out how to construct the object and send it on the request. So I decided to adapted another code I saw here on SO.
The Object I need is this:
{ "code" : xxx }
Here I have a problem. This xxx is a NSData, so I suspect that I have to convert this data to a string, then use this string to build an object and send this on the request.
the server response is also a JSON object, in the form
{ "answer" : "yyy" } where yyy is a number between 10000 and 99999
this is the code I have so far.
- (NSString *)checkData:(NSData) theData {
NSString *jsonObjectString = [self encode:(uint8_t *)theData length:theData.length];
NSString *completeString = [NSString stringWithFormat:@"http://www.server.com/check?myData=%@", jsonObjectString];
NSURL *urlForValidation = [NSURL URLWithString:completeString];
NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation];
[validationRequest setHTTPMethod:@"POST"];
NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil];
[validationRequest release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding: NSUTF8StringEncoding];
NSInteger response = [responseString integerValue];
NSLog(@"%@", responseString);
[responseString release];
return responseString;
}
- (NSString *)encode:(const uint8_t *)input length:(NSInteger)length {
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData *data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t *output = (uint8_t *)data.mutableBytes;
for (NSInteger i = 0; i < length; i += 3) {
NSInteger value = 0;
for (NSInteger j = i; j < (i + 3); j++) {
value <<= 8;
if (j < length) {
value |= (0xFF & input[j]);
}
}
NSInteger index = (i / 3) * 4;
output[index + 0] = table[(value >> 18) & 0x3F];
output[index + 1] = table[(value >> 12) & 0x3F];
output[index + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[index + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
ret
urn [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
}
all this code gives me is errors. Or BAD URL or java exception.
What is wrong with this code?
If you guys prefer to give another solution using the json-framework please tell me how to encode the object using that pair ("code", "my NSData here converted to string")...
thanks for any help.