John Williamson
John Williamson

Reputation: 15

Objective C String to JSON formatting

Quick disclaimer. I've programmed Java for years but this is the first Objective C I've ever written.

I've written some code which almost unfortunately works but frankly hurts my eyes with the number of lines of code and quality. Basically looking for the right way to convert the original string:

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

Into JSON (ignoring the TUHandle 0x280479f50) part which I don't need:

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

Line breaks and indents are NOT important, only that this is valid 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];

Any tips which would make this look a hell of a lot less clunky?

Upvotes: 0

Views: 125

Answers (1)

Gereon
Gereon

Reputation: 17844

Depending on what parts of the format you're comfortable with hardcoding, this may serve.

It assumes that only parts of the input string that look like "x=y" go into the json, and cuts off the last character from y's value, since that's either a "," or the trailing ">".

- (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);
}

Upvotes: 1

Related Questions