简体   繁体   中英

How to convert NSString as JSON Format in 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.

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.

Your revised question is now a case of manipulating NSDictionary, NSString and NSArray objects to obtain the desired format before serialising it as JSON.

You need to manipulate your original data into a dictionary, containing a key/value pair,

log :

...and then serialise that as JSON.

In your loop where you add objects for each logArray item, you could appendString with the required format instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM