Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert NSString as JSON Format in ios5?

Tags:

json

iphone

ios5

I have some String values like this format,

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

I want to convert these strings to JSON using NSJSONSerialization.

I am using the following code to convert the 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 getting output like this ,

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 output like this,

{
"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 don't know how to generate a JSON string in the above format, please suggest a solution.

like image 393
Yuvaraj M Avatar asked Oct 06 '22 20:10

Yuvaraj M


1 Answers

The string you're getting is valid JSON, whereas the string you want is not. So, you won't be able to use the iOS JSON library to generate invalid JSON.

You can test validity by using this online utility,

JSONLint

Hope that helps.

UPDATE: Question has since been revised to show valid JSON as required output.

like image 138
Snips Avatar answered Oct 10 '22 02:10

Snips