我必须使用.Net API,它返回并使用MongoDB ObjectId作为结果和参数
例如,服务器返回
_id": {
"Timestamp": 1478679428,
"Machine": 1031587,
"Pid": 9124,
"Increment": 2344035,
"CreationTime": "/Date(1478679428000)/"
}
以对象 ID 值ObjectId("5822db840fbda323a423c463")
的NSDictionary
形式
我的问题是:如何将上述NSDictionary
_id转换为目标 C 中的字符串值5822db840fbda323a423c463
?
反之亦然,将NSString
5822db840fbda323a423c463
转换为NSDictionary
以作为 api 参数发送?
请注意:我不能更改 api,只能使用它
任何帮助将不胜感激
我发布我的工作结果作为答案,希望以后对其他人有所帮助
用于将NSDictionary
从 API 结果序列化为NSString
- (NSString *)NSStringFromNSDictionary:(NSDictionary *)dict
{
long Timestamp = [[dict objectForKey:@"Timestamp"] longValue];
long Machine = [[dict objectForKey:@"Machine"] longValue];
long Pid = [[dict objectForKey:@"Pid"] longValue];
long Increment = [[dict objectForKey:@"Increment"] longValue];
NSString *oid = [NSString stringWithFormat:@"%08lx%06lx%04lx%06lx", Timestamp, Machine, Pid, Increment];
return oid;
}
用于以NSDictionary
的形式将NSString
序列化回.Net Mongo ObjectId
- (NSDictionary *)NSStringFromNSDictionary:(NSString *)oid
{
long Timestamp = strtol([[oid substringToIndex:8] UTF8String], NULL, 16);
long Machine = strtol([[oid substringWithRange:NSMakeRange(8,6)] UTF8String], NULL, 16);
long Pid = strtol([[oid substringWithRange:NSMakeRange(14,4)] UTF8String], NULL, 16);
long Increment = strtol([[oid substringFromIndex:18] UTF8String], NULL, 16);
NSDictionary * dict = @{@"Timestamp": [NSNumber numberWithLong:Timestamp]
,@"Machine": [NSNumber numberWithLong:Machine]
,@"Pid": [NSNumber numberWithLong:Pid]
,@"Increment": [NSNumber numberWithLong:Increment]
,@"CreationTime": [NSString stringWithFormat:@"/Date(%ld)/",Timestamp*1000]
};
return dict;
}