【问题标题】:Objective C String to JSON formatting目标 C 字符串到 JSON 格式
【发布时间】:2020-09-26 16:01:59
【问题描述】:

快速免责声明。我已经编写 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];

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

【问题讨论】:

  • 也许codereview.stackexchange.com 会是一个更好的地方?您可能应该从使用 item[0]item[1]dict[key] = value 开始。
  • 我想您也可以使用NSRegularExpression 来解析字符串,例如&lt;TUHandle 0x\\d+ ([a-zA-Z]+=[a-zA-Z()]+)+ &gt; 并遍历匹配项。但是,我相信您的解决方案是最简单的方法之一。 Objective-C 永远不会像其他语言那样好看。
  • 谢谢@Sulthan。以前从未见过那个地方。会试一试

标签: json objective-c


【解决方案1】:

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

它假定只有看起来像“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);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多