Reputation: 21
I am using JSON converter to convert a XML string to JSON string. I need to convert this JSON string again back to XML string. Is there any specific methods to do this?
Upvotes: 1
Views: 2742
Reputation: 1971
With this code you can convert JSON to NSDictionary
NSString * jsonString = @"blblblblblb";
NSStringEncoding encoding;
NSData * jsonData = [jsonString dataUsingEncoding:encoding];
NSError * error=nil;
NSDictionary * parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
Please use below code for converting NSDictionary to XML. So you can have JSON to XML converter.
+(NSString*)ConvertDictionarytoXML:(NSDictionary*)dictionary withStartElement:(NSString*)startele
{
NSMutableString *xml = [[NSMutableString alloc] initWithString:@""];
NSArray *arr = [dictionary allKeys];
[xml appendString:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"];
[xml appendString:[NSString stringWithFormat:@"<%@>",startele]];
for(int i=0;i<[arr count];i++)
{
id nodeValue = [dictionary objectForKey:[arr objectAtIndex:i]];
if([nodeValue isKindOfClass:[NSArray class]] )
{
if([nodeValue count]>0){
for(int j=0;j<[nodeValue count];j++)
{
id value = [nodeValue objectAtIndex:j];
if([ value isKindOfClass:[NSDictionary class]])
{
[xml appendString:[NSString stringWithFormat:@"<%@>",[arr objectAtIndex:i]]];
[xml appendString:[NSString stringWithFormat:@"%@",[value objectForKey:@"text"]]];
[xml appendString:[NSString stringWithFormat:@"</%@>",[arr objectAtIndex:i]]];
}
}
}
}
else if([nodeValue isKindOfClass:[NSDictionary class]])
{
[xml appendString:[NSString stringWithFormat:@"<%@>",[arr objectAtIndex:i]]];
if([[nodeValue objectForKey:@"Id"] isKindOfClass:[NSString class]])
[xml appendString:[NSString stringWithFormat:@"%@",[nodeValue objectForKey:@"Id"]]];
else
[xml appendString:[NSString stringWithFormat:@"%@",[[nodeValue objectForKey:@"Id"] objectForKey:@"text"]]];
[xml appendString:[NSString stringWithFormat:@"</%@>",[arr objectAtIndex:i]]];
}
else
{
if([nodeValue length]>0){
[xml appendString:[NSString stringWithFormat:@"<%@>",[arr objectAtIndex:i]]];
[xml appendString:[NSString stringWithFormat:@"%@",[dictionary objectForKey:[arr objectAtIndex:i]]]];
[xml appendString:[NSString stringWithFormat:@"</%@>",[arr objectAtIndex:i]]];
}
}
}
[xml appendString:[NSString stringWithFormat:@"</%@>",startele]];
NSString *finalxml=[xml stringByReplacingOccurrencesOfString:@"&" withString:@"&"];
// NSLog(@"%@",xml);
return finalxml;
}
Upvotes: 2