美文网首页
iOS实现有序json串

iOS实现有序json串

作者: lesmiserables0 | 来源:发表于2020-03-11 22:28 被阅读0次

这段代码源于一个加密需求,为了验证接口加密的数据,需要把NSDictionary 转为有序字符串。
苦思冥想一下午,终于用递归完成了这个需求。

+(NSString *)returnJsonstringwithObject:(id)aObject{
    NSString *  jsonStr = @"";
    if ([aObject isKindOfClass:[NSDictionary class]]) {
        NSString *  jsonStr = [@"" stringByAppendingString:@"{"];
        NSDictionary *tempDic = (NSDictionary *)aObject;
        NSArray *tempKeys = [tempDic allKeys];
        NSArray *keys = [tempKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return [obj1 compare:obj2];
        }];
        if (keys.count > 0) {
            for (NSString *key in keys) {
                jsonStr = [jsonStr stringByAppendingFormat:@"\"%@\":%@,",key,[self returnJsonstringwithObject:[tempDic objectForKey:key]]];
            }
            jsonStr = [jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)];
        }
         jsonStr =[jsonStr stringByAppendingString:@"}"];
        return jsonStr;
    }else if ([aObject isKindOfClass:[NSArray class]]){
        jsonStr =[jsonStr stringByAppendingString:@"["];
        NSArray *tempArr = (NSArray *)aObject;
        if (tempArr.count > 0) {
            for (id object in tempArr) {
                jsonStr = [jsonStr stringByAppendingFormat:@"%@,",[self returnJsonstringwithObject:object]];
            }
            jsonStr = [jsonStr substringWithRange:NSMakeRange(0, jsonStr.length-1)];
        }
        jsonStr= [jsonStr stringByAppendingString:@"]"];
        return jsonStr;
    }else{
        jsonStr = [jsonStr stringByAppendingFormat:@"\"%@\"",aObject];
        return  jsonStr;
    }
    return jsonStr;
}

使用中如有问题,请在评论里指出。

相关文章

网友评论

      本文标题:iOS实现有序json串

      本文链接:https://www.haomeiwen.com/subject/qiskjhtx.html