将从PubNub接收的消息转换为Dictionary对象

时间:2017-03-07 10:30:31

标签: ios objective-c nsdictionary pubnub

我有以下用于接收PubNub消息的对象C代码。

- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {


    NSLog(@"Received message: %@ on channel %@ at %@", message.data.message,
    message.data.subscribedChannel, message.data.timetoken);

}

返回的数据是

Received message: (
    {
    key = userName;
    value = Enoch;
},
    {
    key = photoID;
    value = 3;
},
    {
    key = userID;
    value = 1;
},
    {
    key = actionType;
    value = chat;
},
    {
    key = message;
    value = H;
}
) on channel chat at 14888810882049989

我想通过使用“密钥”将消息解析为字典对象以访问“值”

我是客观C编程的新手,不知道该怎么做。

请帮忙。

2 个答案:

答案 0 :(得分:1)

遍历消息数组并在字典中设置键值。

NSArray *array = (NSArray*)message.data.message;
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for (NSDictionary *item in array) {
    [dic setObject:[item objectForKey:@"value"] forKey:[item objectForKey:@"key"]];
}
NSLog(@"%@", dic);

NSArray *array = (NSArray*)message.data.message;
NSArray *values = [array valueForKey: @"value"];
NSArray *keys = [array valueForKey: @"key"];
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
NSLog(@"%@", dic);

答案 1 :(得分:0)

您可以使用以下方法解析数据并将其转换为字典

ChatterBoxMessage *chatterBoxMessage = [[ChatterBoxMessage alloc] initFromDictionary: message.data.message  withTimeToken: message.data.timetoken];

[chatterBoxMessage asDictionary];

通过此方法,您将获得dictionary

以上ChatterBoxMessage是一个PubNub库类。

您还可以解析以下数据:

for (NSDictionary *objectData in message.data.message) {
      NSLog(@"Value : %@",objectData[@"value"]);
      NSLog(@"Key : %@",objectData[@"key"]);
}