我必须使用.Net API,该API返回并使用MongoDB ObjectId作为结果和参数
例如,服务器返回
_id": {
"Timestamp": 1478679428,
"Machine": 1031587,
"Pid": 9124,
"Increment": 2344035,
"CreationTime": "/Date(1478679428000)/"
}
以NSDictionary
的形式获取ObjectID值ObjectId("5822db840fbda323a423c463")
我的问题是:如何在目标C中将NSDictionary
_id以上的值转换为字符串值5822db840fbda323a423c463
?
反之亦然,将NSString
5822db840fbda323a423c463
转换为NSDictionary
以作为api参数发送?
请注意:我无法更改api ,只能使用它
任何帮助将不胜感激
答案 0 :(得分:0)
我将我的工作结果作为答案发布,希望以后对其他人有帮助
用于将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;
}
用于将NSString
序列化为NSDictionary
形式的.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;
}