我正在使用SignalR-ObjC的应用程序。我已经设置了与服务器的连接并且正在接收正确的数据,但是响应对象让我失望。我试图解析对JSON和字典的响应,但看起来SignalR-ObjC将响应包装在额外的数据中,这阻止我将其解析为JSON。
这是我的回答的一部分:
RESPONSE: {
A = (
"{\"NotificationType\":1,\"TelemetryDetails\":{\"serialNumber\":\"xxx\",\"name\":\"xxx\",,\"protectedDeviceIp\":\"xxx\"},{\"endpoint\":\"xxx\",\"ip\":\"xxx\",\"domain\":null,\"latitude\":null,\"longitude\":null,\"protectedDeviceId\":\"xxx\",\"protectedDeviceIp\":\"xxx\"}]}]},\"CommandResult\":null,\"FortressBoxSerialNumber\":\"xxx\"}"
);
H = NotificationsHub;
M = notificationData;
}
在所有其他平台上,我的回答只是" A"的价值。在这儿。不确定为什么SignalR-ObjC用所有这些额外数据(中心信息)包装响应。
我的代码:
-(void)SignalR{
WebServices *services = [[WebServices alloc] init];
SRHubConnection *hubConnection = [SRHubConnection connectionWithURLString:@"xxx"];
SRHubProxy *proxy = [hubConnection createHubProxy:@"xxx"];
[services callGetSRAlertGroupNames:^(NSMutableArray *alertGroupNameArray){
NSLog(@"SR ALERT GROUP NAMES: %@", alertGroupNameArray);
[services callGetSRNotificationGroupNames:^(NSMutableArray *notificationGroupNameArray) {
NSLog(@"SR NOTIFICATION GROUP NAMES: %@", notificationGroupNameArray);
NSArray *combinedArray=[alertGroupNameArray arrayByAddingObjectsFromArray:notificationGroupNameArray];
// Register for connection lifecycle events
[hubConnection setStarted:^{
NSLog(@"Connection Started");
for (NSString *groupName in combinedArray ){
[proxy invoke:@"Subscribe" withArgs:@[groupName] completionHandler:nil];
}
}];
[hubConnection setReceived:^(NSString *strData) {
NSLog(@"RESPONSE: %@", strData);
NSError *jsonError;
NSData *objectData = [strData dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(@"JSON DATA - %@", json);
}];
[hubConnection setConnectionSlow:^{
NSLog(@"Connection Slow");
}];
[hubConnection setReconnecting:^{
NSLog(@"Connection Reconnecting");
}];
[hubConnection setReconnected:^{
NSLog(@"Connection Reconnected");
}];
[hubConnection setClosed:^{
NSLog(@"Connection Closed");
}];
[hubConnection setError:^(NSError *error) {
NSLog(@"Connection Error %@",error);
}];
[hubConnection start];
}];
}];
}
如果我复制并粘贴" A"在我的响应对象中," strData"正在编码,解析它的代码工作正常。但是,如果我传递整个响应对象,它就会中断。
请记住,我的响应对象看起来是一个字符串,如何提取" A"或者阻止SignalR-ObjC用这些额外数据包装我的回复?
答案 0 :(得分:0)
通过将hubConnection setReceived更改为以下内容解决了我的问题:
[hubConnection setReceived:^(NSDictionary *strData) {
NSLog(@"RESPONSE: %@", [strData valueForKey:@"A"]);
NSString *str = [strData valueForKey:@"A"][0];
NSError *jsonError;
NSData *objectData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(@"JSON DATA - %@", json);
}];
解决问题的原因是将响应对象类型从NSString更改为NSDictionary,然后实现获取“A”的valueForKey给了我一个数组,所以我必须在编码/序列化之前获取该数组中的第一个值。