Json字符串中字典项顺序

2017-07-10  本文已影响157人  心亦逸风

简介

之前我有做一个问卷的模块,题目是后台以数组的形式给我,在上传问卷答案的时候,答案又是以字典的形式给后台,转换成json字符串后有一个固定顺序,而后台又需要按照给的顺序排列。

一般Json字符串转换

+(NSString *)getJsonStr:(id)jsonData
{
    if ([NSJSONSerialization isValidJSONObject:jsonData])
    {
        NSData *data = [NSJSONSerialization dataWithJSONObject:jsonData options:NSJSONWritingPrettyPrinted error:nil];
        return  [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    }
    return nil;
}

这是我来之前别人写的公共类,就是转换成json字符串用的,我在转换问卷答案字典的时候自然不能以我需要的顺序转换了。

我的方式

思路大概是先获得字典的key的数组,对这个数组进行想要的排序,然后根据这个数组的顺序自己拼接为相应的json字符串。

- (NSString *)getOrderDicJsonStr:(NSMutableDictionary *)dic
{
    WS(ws);
    NSArray *allKeys = [dic allKeys];
    NSArray *sortArray = [allKeys sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSString *profileId1 = (NSString *)obj1;
        NSString *profileId2 = (NSString *)obj2;
        int intObj1 = [[ws.qaLocationDictionary objectForKey:profileId1] intValue];
        int intObj2 = [[ws.qaLocationDictionary objectForKey:profileId2] intValue];
        if (intObj1 < intObj2) {
            return NSOrderedAscending;
        } else if (intObj1 > intObj2) {
            return NSOrderedDescending;
        } else {
            return NSOrderedSame;
        }
    }];
    NSMutableString *jsonStr = [[NSMutableString alloc] initWithString:@"{"];
    NSString *profileId;
    for (profileId in sortArray) {
        [jsonStr appendFormat:@"\n\"%@\":\"%@\",",profileId,[dic objectForKey:profileId]];
    }
    [jsonStr deleteCharactersInRange:NSMakeRange(jsonStr.length-1, 1)];
    [jsonStr appendString:@"\n}"];
    return [NSString stringWithString:jsonStr];
}

这里的qaLocationDictionary的key是每到题目的id,value是每道题目的序号(从0开始)。
字典的json字符串大概是这样的形式
"{\n\"profileId\":\"value\",\n\"profileId\":\"value\"\n}"

觉得有用的话可以点个赞,谢谢!

上一篇 下一篇

猜你喜欢

热点阅读