IT虾米网

iOS Json的解析与创建详解

xmjava 2018年06月24日 手机开发 340 0
+ (NSString *)voiceMessageConentWithEntity:(VMessageEntity *)entity{ 
 
    NSLog(@"entity.voiceMessage.voicemd5 == %@",entity.voiceMessage.voicemd5); 
 
    if (!entity) { 
 
        return nil; 
 
    } 
 
    VChatVoiceEntity *voiceMessage = entity.voiceMessage; 
 
    if (!voiceMessage) { 
 
        return nil; 
 
    } 
 
    NSString *voicemd5 = voiceMessage.voicemd5; 
 
    NSString *duration = voiceMessage.duration; 
 
    if (entity.messageType == VMessageTypeVoice) { 
 
        NSMutableDictionary *rootDict = [NSMutableDictionary dictionary]; 
 
        if (voicemd5) { 
 
            [rootDict setObject:voicemd5 forKey:@"md5"]; 
 
        } 
 
        if (duration) { 
 
            [rootDict setObject:duration forKey:@"duration"]; 
 
        } 
 
       NSError *error = nil; 
 
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:rootDict options:NSJSONWritingPrettyPrinted error:&error]; 
 
        if (error) { 
 
            NSLog(@"%@", error); 
 
        } 
 
        NSString *json = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; 
 
        return json; 
 
    }else{ 
 
        return nil; 
 
    } 
 
 
} 
 
 
+ (VChatVoiceEntity *)voiceWithJson:(NSString *)json{ 
 
    if (!json.length) { 
 
        return nil; 
 
    } 
 
    NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding]; 
 
    NSError *error = nil; 
 
    NSDictionary *root = [NSJSONSerialization JSONObjectWithData:jsonData 
 
                                                         options:NSJSONReadingMutableLeaves 
 
                                                           error:&error]; 
 
    if (root) { 
 
        VChatVoiceEntity *voiceMessage = [[VChatVoiceEntity alloc] init]; 
 
        voiceMessage.voicemd5 = [root objectForKey:@"md5"]; 
 
        voiceMessage.duration = [root objectForKey:@"duration"]; 
 
        return voiceMessage; 
 
    } 
 
    return nil; 
 
 
}

发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

ios 时间类转化为字符串详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。