How to convert NSString to JSON format in ios5?

I have some String values, such as this format,

[INFO]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [26]  [Hello]  [;]

I want to convert these strings to JSON using NSJSONSerialization.

I use the following code to convert strings,

 for (i = 0; i < [logArray count]; i++) 
{
    individualLogInfoArray = [[logArray objectAtIndex:i] componentsSeparatedByString:kDelimitterSpace];
    [dictionaryArray addObject:individualLogInfoArray];

}

finalLogDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:dictionaryArray,@"Log", nil];
    NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalLogDictionary 
                                                   options:NSJSONWritingPrettyPrinted
                                                     error:&error];

NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JsonString = %@",jsonString);

Then I get the output as follows:

JsonString = {
  "Log" : [
    "[INFO]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [26]  [Hello]  [;]",
    "[DEBUG]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [27]  [hi]  [;]",
    "[INFO]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [28]  [Its  there]  [;]",
    "[PROD]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [29]  [Welcome]  [;]"
  ]
}

but I want it to be so

{
"log": "[INFO]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [26]  [Hello],[INFO]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [26]  [Hello],[INFO]  [Tue Aug 21 14:54:22 2012]  [ViewController]  [26]  [Hello]"

}

I do not know how to create a JSON string in the above format, please suggest a solution.

+5
source share
2 answers

The string you receive is valid JSON, while the string you need is not. Thus, you cannot use the iOS JSON library to create invalid JSON.

You can validate using this online utility,

JSONLint

Hope this helps.

: , JSON .

+4

- NSDictionary, NSString NSArray JSON.

, /,

log:

... JSON.

, logArray, appendString .

0

All Articles