1. json生成
bool sendCmd(int msg_id,NSString* type,NSString* param)
{
NSDictionary *dic = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithInt:mSession], @"token", [NSNumber numberWithInt:msg_id], @"msg_id", nil, nil];//不可变字典
NSMutableDictionary *mutableDic = [NSMutableDictionary dictionaryWithDictionary:dic];//可变字典
if(type!=nil) [mutableDic setObject:type forKey:@"type"];
if(param!=nil) [mutableDic setObject:param forKey:@"param"];
NSError *parseError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:mutableDic options:NSJSONWritingPrettyPrinted error:&parseError];
NSString *szCmd = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
szCmd = [szCmd stringByReplacingOccurrencesOfString:@" " withString:@""];//去掉空格
szCmd = [szCmd stringByReplacingOccurrencesOfString:@"\r" withString:@""];//去掉回车
szCmd = [szCmd stringByReplacingOccurrencesOfString:@"\n" withString:@""];//去掉换行
NSLog(@"%@",szCmd);
return sendData(szCmd);
}
2. json解析
bool OnReceive(uint8_t* buf, long len)
{
NSData *json = [NSData dataWithBytes:buf length:len];
NSMutableData *jsonData = [[NSMutableData alloc] init];
[jsonData appendData:json];
NSString *szjson = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(@"%@", szjson);
NSError *error = nil;
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
NSNumber *msg_id = [jsonDic objectForKey:@"msg_id"];
switch([msg_id intValue]) {
case 257: {
NSNumber *session = [jsonDic objectForKey:@"param"];
int mSession = [session intValue];
}
break;
default:
break;
}
return true;
}