将 NSData 转换为 NSString - NSLog 限制
Convert NSData to NSString - NSLog limitation
我试图在 Zendesk 中将 NSData
转换为 NSString
,但得到的字符串不完整,或者至少无法完全解码 data
.
当我curl
以下命令时:
curl https://mySubdomain.zendesk.com/api/v2/users/1038194884/tickets/requested.json -v -u myLogin:myPassword
我得到了正确的响应,它列出了该用户的所有工单,响应如下:
< HTTP/1.1 200 OK < Server: nginx < Date: Sat, 28 Jan 2017 19:50:16
GMT < Content-Type: application/json; charset=UTF-8 <
Content-Length: 12576 < Connection: keep-alive <
X-Zendesk-API-Version: v2 < X-Zendesk-Application-Version: v8.28 <
X-Frame-Options: SAMEORIGIN < X-Rate-Limit: 400 <
X-Rate-Limit-Remaining: 399 < Strict-Transport-Security:
max-age=31536000; < X-UA-Compatible: IE=Edge,chrome=1 < ETag:
"98b10cfcb2f1577122a1662926f9565c" < Cache-Control: must-revalidate,
private, max-age=0 < X-Zendesk-Origin-Server:
app2.pod7.fra1.zdsys.com < X-Request-Id:
db8b90fd-e3a3-452d-c5ea-ecf4bbd76e89 < X-Runtime: 0.303978 <
X-Rack-Cache: miss < X-Zendesk-Request-Id: bdfd524aa5520cf39e57 <
X-Content-Type-Options: nosniff
当我尝试在 objective-C
中从 iOS
应用程序执行相同的操作时,响应几乎相同,如下所示:
"Cache-Control" = "must-revalidate, private, max-age=0";
Connection = "keep-alive";
"Content-Encoding" = gzip;
"Content-Type" = "application/json; charset=UTF-8";
Date = "Sat, 28 Jan 2017 20:36:38 GMT";
Etag = "\"98b10cfcb2f1577122a1662926f9565c\"";
Server = nginx;
"Strict-Transport-Security" = "max-age=31536000;";
"Transfer-Encoding" = Identity;
"X-Content-Type-Options" = nosniff;
"X-Frame-Options" = SAMEORIGIN;
"X-Rack-Cache" = miss;
"X-Rate-Limit" = 400;
"X-Rate-Limit-Remaining" = 399;
"X-Request-Id" = "53c1b462-2dec-4c46-cc60-ecf4bbd76e89";
"X-Runtime" = "0.209525";
"X-UA-Compatible" = "IE=Edge,chrome=1";
"X-Zendesk-API-Version" = v2;
"X-Zendesk-Application-Version" = "v8.28";
"X-Zendesk-Origin-Server" = "app4.pod7.fra1.zdsys.com";
"X-Zendesk-Request-Id" = 675ae5b4ff78fbe7
问题是当我尝试将 data
转换为 dictionary
或 NSString
时,我得到了不完整的 string
。这是我正在使用的代码:
NSString *urlUser = [NSString stringWithFormat:@"https://mySubdomain.zendesk.com/api/v2/users/1038194884/tickets/requested.json"];
NSURL *url = [[NSURL alloc] initWithString:urlUser];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue : @"application/json"
forHTTPHeaderField : @"Content-Type" ];
NSString *authStr = @"username:password";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"finished");
if (!error)
{
NSLog(@"%@", data);
NSLog(@"RESPONSE: %@", response);
NSLog(@"length: %lu", data.length);
//Determine if string is null-terminated
char lastByte;
[data getBytes:&lastByte range:NSMakeRange([data length]-1, 1)];
NSString *str;
if (lastByte == 0x0) {
//string is null-terminated
str = [NSString stringWithUTF8String:[data bytes]];
} else {
//string is not null-terminated
str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
NSLog(@"string length: %lu", str.length);
NSLog(@"%@", str);
NSLog(@"stop");
}
}];
[task resume];
顺便说一句,data
长度与 curl
响应中的长度相同。
记录的字符串:
{"tickets":[{"url":"https://mySubdomain.zendesk.com/api/v2/tickets/407.json","id":407,"external_id":null,"via":{"channel":"mobile_sdk","source":{"from":{},"to":{},"rel":"mobile_sdk"}},"created_at":"2017-01-26T10:48:28Z","updated_at":"2017-01-26T11:05:42Z","type":null,"subject":"Comentário
sobre exercício.","raw_subject":"Comentário sobre
exercício.","description":"Nome do usuário: bruna villete\nObjectId:
qHQzNbjUzy\nPlano: Iron Training - brazil\n\nDETALHES DO EXERCÍCIO:
\nTitulo: CADEIRA EXTENSORA\nObjectId: qvq5deXxD9\nPerfil: MULHER
INICIANTE\nFrequência: 5\nPeríodo: Semana1\nSérie: Serie
B\n\nCOMENTÁRIO:
\nbom","priority":null,"status":"solved","recipient":null,"requester_id":1038194884,"submitter_id":1038194884,"assignee_id":3030446965,"organization_id":null,"group_id":24989965,"collaborator_ids":[],"forum_topic_id":null,"problem_id":null,"has_incidents":false,"is_public":true,"due_at":null,"tags":["seriecomment"],"custom_fields":[],"satisfaction_rating":null,"sharing_agreement_
First convert the JSON response to NSDictionary
然后像往常一样从字典中访问您的 NSString。 (或您 JSON 回复中的任何其他 value/key)
NSString *myStr = [json objectForKey:@"someKey"];
正如我在评论中告诉您的那样,NSLog
语句似乎切断了字符串。一切正常。
要处理您的数据,请将其转换为 json 对象并像这样使用它:
// convert the response data to json
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!error) {
NSLog(@"json parsing succeeded.");
}
// access your data
NSArray *tickets = json[@"tickets"];
我试图在 Zendesk 中将 NSData
转换为 NSString
,但得到的字符串不完整,或者至少无法完全解码 data
.
当我curl
以下命令时:
curl https://mySubdomain.zendesk.com/api/v2/users/1038194884/tickets/requested.json -v -u myLogin:myPassword
我得到了正确的响应,它列出了该用户的所有工单,响应如下:
< HTTP/1.1 200 OK < Server: nginx < Date: Sat, 28 Jan 2017 19:50:16 GMT < Content-Type: application/json; charset=UTF-8 < Content-Length: 12576 < Connection: keep-alive < X-Zendesk-API-Version: v2 < X-Zendesk-Application-Version: v8.28 < X-Frame-Options: SAMEORIGIN < X-Rate-Limit: 400 < X-Rate-Limit-Remaining: 399 < Strict-Transport-Security: max-age=31536000; < X-UA-Compatible: IE=Edge,chrome=1 < ETag: "98b10cfcb2f1577122a1662926f9565c" < Cache-Control: must-revalidate, private, max-age=0 < X-Zendesk-Origin-Server: app2.pod7.fra1.zdsys.com < X-Request-Id: db8b90fd-e3a3-452d-c5ea-ecf4bbd76e89 < X-Runtime: 0.303978 < X-Rack-Cache: miss < X-Zendesk-Request-Id: bdfd524aa5520cf39e57 < X-Content-Type-Options: nosniff
当我尝试在 objective-C
中从 iOS
应用程序执行相同的操作时,响应几乎相同,如下所示:
"Cache-Control" = "must-revalidate, private, max-age=0"; Connection = "keep-alive"; "Content-Encoding" = gzip; "Content-Type" = "application/json; charset=UTF-8"; Date = "Sat, 28 Jan 2017 20:36:38 GMT"; Etag = "\"98b10cfcb2f1577122a1662926f9565c\""; Server = nginx; "Strict-Transport-Security" = "max-age=31536000;"; "Transfer-Encoding" = Identity; "X-Content-Type-Options" = nosniff; "X-Frame-Options" = SAMEORIGIN; "X-Rack-Cache" = miss; "X-Rate-Limit" = 400; "X-Rate-Limit-Remaining" = 399; "X-Request-Id" = "53c1b462-2dec-4c46-cc60-ecf4bbd76e89"; "X-Runtime" = "0.209525"; "X-UA-Compatible" = "IE=Edge,chrome=1"; "X-Zendesk-API-Version" = v2; "X-Zendesk-Application-Version" = "v8.28"; "X-Zendesk-Origin-Server" = "app4.pod7.fra1.zdsys.com"; "X-Zendesk-Request-Id" = 675ae5b4ff78fbe7
问题是当我尝试将 data
转换为 dictionary
或 NSString
时,我得到了不完整的 string
。这是我正在使用的代码:
NSString *urlUser = [NSString stringWithFormat:@"https://mySubdomain.zendesk.com/api/v2/users/1038194884/tickets/requested.json"];
NSURL *url = [[NSURL alloc] initWithString:urlUser];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request addValue : @"application/json"
forHTTPHeaderField : @"Content-Type" ];
NSString *authStr = @"username:password";
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat: @"Basic %@",[authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:@"Authorization"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"finished");
if (!error)
{
NSLog(@"%@", data);
NSLog(@"RESPONSE: %@", response);
NSLog(@"length: %lu", data.length);
//Determine if string is null-terminated
char lastByte;
[data getBytes:&lastByte range:NSMakeRange([data length]-1, 1)];
NSString *str;
if (lastByte == 0x0) {
//string is null-terminated
str = [NSString stringWithUTF8String:[data bytes]];
} else {
//string is not null-terminated
str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}
NSLog(@"string length: %lu", str.length);
NSLog(@"%@", str);
NSLog(@"stop");
}
}];
[task resume];
顺便说一句,data
长度与 curl
响应中的长度相同。
记录的字符串:
{"tickets":[{"url":"https://mySubdomain.zendesk.com/api/v2/tickets/407.json","id":407,"external_id":null,"via":{"channel":"mobile_sdk","source":{"from":{},"to":{},"rel":"mobile_sdk"}},"created_at":"2017-01-26T10:48:28Z","updated_at":"2017-01-26T11:05:42Z","type":null,"subject":"Comentário sobre exercício.","raw_subject":"Comentário sobre exercício.","description":"Nome do usuário: bruna villete\nObjectId: qHQzNbjUzy\nPlano: Iron Training - brazil\n\nDETALHES DO EXERCÍCIO: \nTitulo: CADEIRA EXTENSORA\nObjectId: qvq5deXxD9\nPerfil: MULHER INICIANTE\nFrequência: 5\nPeríodo: Semana1\nSérie: Serie B\n\nCOMENTÁRIO: \nbom","priority":null,"status":"solved","recipient":null,"requester_id":1038194884,"submitter_id":1038194884,"assignee_id":3030446965,"organization_id":null,"group_id":24989965,"collaborator_ids":[],"forum_topic_id":null,"problem_id":null,"has_incidents":false,"is_public":true,"due_at":null,"tags":["seriecomment"],"custom_fields":[],"satisfaction_rating":null,"sharing_agreement_
First convert the JSON response to NSDictionary
然后像往常一样从字典中访问您的 NSString。 (或您 JSON 回复中的任何其他 value/key)
NSString *myStr = [json objectForKey:@"someKey"];
正如我在评论中告诉您的那样,NSLog
语句似乎切断了字符串。一切正常。
要处理您的数据,请将其转换为 json 对象并像这样使用它:
// convert the response data to json
NSError *error = nil;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if (!error) {
NSLog(@"json parsing succeeded.");
}
// access your data
NSArray *tickets = json[@"tickets"];