• 服务器返回的数据将Unicode码转成汉字


    当我们请求接口的时候,服务器会返回一些数据,当我们打印的时候就会发现,打印出来的是unicode码,不是汉字。

    这时候需要我们自己手动处理一下,让打印的时候输出汉字的格式。

    方法如下:

    新增一个分类,在分类中,重写描述的方法,如下:

    /**
     *  集合类型打log
     */
    @implementation NSArray (log)
    
    - (NSString *)description{
        return [self descriptionWithLocale:nil];
    }
    
    - (NSString *)descriptionWithLocale:(id)locale{
        NSMutableString * string = [[NSMutableString alloc]init];
        [string appendString:@"[
    "];
        for (int i = 0; i < self.count; i++) {
            [string appendFormat:@"	第%d个 -- %@ 
    ",i,self[i] ];
        }
        [string stringByAppendingString:@"]
    "];
        return string;
    }
    
    
    @end
    
    
    
    @implementation NSDictionary (Log)
    
    - (NSString *)jsonDescription {
        // 参考了此博客 https://www.jianshu.com/p/f14b4cb1435b .
        // NSString默认使用的是UTF-16,转出UTF-8就能打印了
        NSError * error = nil ;
        NSData *data = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
        
        if (error) {
            NSMutableString *strM = [NSMutableString stringWithString:@"{
    "];
            [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                [strM appendFormat:@"	%@ = %@ ;
    ", key, obj];
            }];
            [strM appendString:@"}
    "];
            return strM;
            
        }
        
        NSString *newString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        newString = [newString stringByReplacingOccurrencesOfString:@"\" withString:@""] ;
        return newString ;
    }
    
    - (NSString *)description{
        return [self descriptionWithLocale:nil];
    }
    
    - (NSString *)descriptionWithLocale:(id)locale
    {
    
        if ([NSJSONSerialization isValidJSONObject:self]) {
            return [self jsonDescription];
        }
        // 原来的写法,格式上有点问题,但是转中文是没问题的
        NSMutableString *strM = [NSMutableString stringWithString:@"{
    "];
    
        [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [strM appendFormat:@"	%@ = %@ ;
    ", key, obj];
        }];
    
        [strM appendString:@"}
    "];
    
        return strM;
    }
    
    @end
  • 相关阅读:
    C# 解决组合优化问题
    <@spring.message "index.title"/>
    服务容错处理库Polly使用
    Pycharm使用入门
    JS知识点
    design pattern
    java的NIO
    Promise
    Docker Compose + Spring Boot + Nginx + Mysql
    苹果开发者账号如何多人协作进行开发和真机调试XCode
  • 原文地址:https://www.cnblogs.com/lyz0925/p/11609486.html
Copyright © 2020-2023  润新知