码迷,mamicode.com
首页 > 移动开发 > 详细

ios Json的解析与创建

时间:2015-05-27 10:21:08      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

之前写过类似微信的语音功能,这里用到了json解析与创建

+ (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;


}

ios Json的解析与创建

标签:

原文地址:http://blog.csdn.net/u011404663/article/details/46038527

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!