zoukankan      html  css  js  c++  java
  • 服务器返回的数据将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
  • 相关阅读:
    nginx能访问html静态文件但无法访问php文件
    LeetCode "498. Diagonal Traverse"
    LeetCode "Teemo Attacking"
    LeetCode "501. Find Mode in Binary Search Tree"
    LeetCode "483. Smallest Good Base" !!
    LeetCode "467. Unique Substrings in Wraparound String" !!
    LeetCode "437. Path Sum III"
    LeetCode "454. 4Sum II"
    LeetCode "445. Add Two Numbers II"
    LeetCode "486. Predict the Winner" !!
  • 原文地址:https://www.cnblogs.com/lyz0925/p/11609486.html
Copyright © 2011-2022 走看看