首页 > 解决方案 > 目标 C 字符串到 JSON 格式

问题描述

快速免责声明。我已经编写 Java 多年,但这是我编写的第一个 Objective C。

我写了一些代码,不幸的是它几乎可以工作,但坦率地说,代码行数和质量伤害了我的眼睛。基本上是在寻找转换原始字符串的正确方法:

<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>

进入我不需要的 JSON(忽略 TUHandle 0x280479f50)部分:

{"value": "07700000000",
"normalizedValue": "(null)",
"type": "PhoneNumber",
"isoCountryCode": "(null)"}

换行和缩进并不重要,只是这是有效的 JSON

        //Format of string
        //<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>
        NSString *original = [NSString stringWithFormat:@"%@", hand];

        //Trim off unused stuff
        NSRange startKeyValues = [original rangeOfString:@"type="];
        NSRange endKeyValues = [original rangeOfString:@">"];
        NSRange rangeOfString = NSMakeRange(startKeyValues.location, endKeyValues.location - startKeyValues.location);
        NSString *keysValues = [original substringWithRange:rangeOfString];

        //Create a dictionary to hold the key values
        NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:10];

        //Split the keysValuesstring
        NSArray *items = [keysValues componentsSeparatedByString:@","];

        for (NSString* o in items)
        {
            //Create key value pairs
            NSArray *item = [o componentsSeparatedByString:@"="];
            NSString *key=[item objectAtIndex:0]; 
            NSString *value=[item objectAtIndex:1];
            [dict setObject:value forKey:key];
        }

        [dict setObject:currentUUID forKey:@"uid"];

        //Convert to Json Object
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];

有什么技巧可以让这看起来不那么笨重吗?

标签: jsonobjective-c

解决方案


根据您对硬编码感到满意的格式部分,这可能会起作用。

它假定只有看起来像“x=y”的部分输入字符串进入 json,并从 y 的值中截断最后一个字符,因为它要么是“,”,要么是尾随的“>”。

- (void) tuhandleToJSON {
    NSString* input = @"<TUHandle 0x280479f50 type=PhoneNumber, value=07700000000, normalizedValue=(null), isoCountryCode=(null)>";

    NSMutableDictionary<NSString*, NSString*>* dict = [NSMutableDictionary dictionary];
    NSArray* tokens = [input componentsSeparatedByString:@" "];
    for (NSString* token in tokens) {
        NSArray<NSString*>* parts = [token componentsSeparatedByString:@"="];
        if (parts.count != 2) {
            continue;
        }

        NSString* key = parts[0];
        NSString* value = parts[1];
        NSUInteger index = value.length - 1;

        dict[key] = [value substringToIndex:index];
    }

    NSError* error;
    NSData* data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

    NSString* json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"%@", json);
}

推荐阅读