XML to JSON conversion in ios - ios

i'm trying to convert a simple xml document in Xcode to JSON. The problem is keep returning nil.
This is my code:
NSURL *url = [[NSURL alloc] initFileURLWithPath:#"http://www.w3schools.com/xml/note.xml"];
NSData *xmlData = [[NSData alloc] initWithContentsOfURL:url];
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLData:xmlData error:&parseError];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionary
options:NSJSONWritingPrettyPrinted
error:&error];
NSLog(#"%#", jsonData);
Error message:
[NSJSONSerialization dataWithJSONObject:options:error:]: value parameter is nil'

As rmaddy said, try printing parseError. If parseError is Nil, then try printing the xmlDictionary, and check if the dictionary is created correctly.
If xmlDictionary is also Nil, then check the xmlData, which should be fine, in which case the dictionaryForXMLData method must be verified if it checks for any conditions.
Hope I helped.

Related

How to parse {status:0,val:450} from a HTML response

i want to take 450
from the following:
NSString {status:0,val:450}
using objective c:
{status:0,val:450}
Please suggest me answer
I cannot completely understand your question . I think you have you have an JSON data like:
{
status:0;
val:450;
}
If you want this data in your app. You want to do
NSURL *blogURL = [NSURL URLWithString:#"https://your url here"];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSDictionary *data = [dataDictionary objectForKey:#"status"];
NSDictionary *item = [data objectForKey:#"val"];
Your JSON Data get in Dictionary format. You can access the Data using the Key. In here your keys are status and val.
I hope this links are help for you.
fetch parse json ios programming tutorial
and this Link:
json parsing in ios

Null JSON response

NSString *connection = #"http:"(link);
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:connection];
NSString *json = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
NSLog(#"\nJSON: %# \n Error: %#", json, error);
if(!error) {
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonData);
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
NSLog(#"JSON: %#", jsonDict);
}
});
The above code returns :
JSON: "{\"value\":[{\"Id\":\" }}
but
NSData is 69746963 735c222c 5c224973 41767469 76655c22 3a5c2231 5c222c
and jsonDict returns (null).
I am confused what may be going on.
Can somebody please help me figure it out.
I am trying to get the JSON data but it returns null.
Thanks
You say the server gave you this:
JSON: "{\"value\":[{\"Id\":\" }}
If I remove the backslashes that were added by the NSLog command, the actual JSON that you received was
{"value":[{"Id":" }}
That isn't valid JSON. That's all there is to it; the server sent you rubbish data, and there is no way to get any information from it. Contact the people creating the server software and ask them to fix the problem.
And you really, really need to distinguish between what an object really contains, and what NSLog prints. NSLog prints the contents of an NSData object by displaying each byte as two hexadecimal digits.
Try one of these (array or dictionary) without converting it into JSON, depending on what u want :
NSString *connection = #"http://(link)";
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSDictionary *jsonDict = [NSDictionary dictionaryWithContentsOfURL:[NSURL URLWithString:connection]];
NSArray *jsonArray = [NSArray arrayWithContentsOfURL:[NSURL URLWithString:connection]];
NSLog(#"DICT: %# ARRAY: %#", jsonDict, jsonArray);
});
I haven't tried it, please paste results?
By the look of your NSString response, it starts with { and ends with } which means it is a NSDictionary.
Change :
NSMutableArray *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
to :
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:nil error:&error];

Appending data from several url JSON calls - into one NSDictionary

So, i have a loop where i repeatedly call an url, which returns contacts in JSON format.
Since i call the url more than once, i want to add it all up, an ultimately end up with a NSDictionary, containing contacts for all the url calls.
What i'm doing now, is appending the data for each iteration:
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
[data appendData:response];
and when the loop is over i try to make it into a NSDictionary:
// Loop over - create Dict from all the data.
NSDictionary *JSONDataFinal = [NSJSONSerialization JSONObjectWithData:data
options:0 error:&error2];
I get an error: "garbage at end" and believe the approach is wrong, since it doesn't know how to put data from each consecutive call into the same key, and not create a key for each call.
Should i create a Dictionary for each iteration - and combine them in the end?
You can append data to a NSMutableDictionary after each call.
NSMutableDictionary* jsonDict = [[NSMutableDictionary alloc] init];
for (...) {
...
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSDictionary *JSONData = [NSJSONSerialization JSONObjectWithData:data
options:0 error:&error2];
[jsonDict addEntriesFromDictionary:JSONData];
}
Create different dictionary for each json data and store in main array like this:
NSMutableArray *arrAllContacts = [NSMutableArray array];
//here arrJsonURL which stores all url for contacts
for(int i=0; i<[arrJsonURL count]; i++)
{
//create request
...............
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
[data appendData:response];
NSError *error = nil;
//get dictionary from json data
NSDictionary *dictContact = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
[arrAllContacts addObject:dictContact];
}

impossible to parse a url containing "and space in xcode

I'm trying to parse json in a url like:
NSError *error = nil;
NSString *sampleUrl= #"http://xbmc:xbmc#192.168.1.23:8080/jsonrpc?request={\"jsonrpc\":%20\"2.0\",%20\"method\":%20\"VideoLibrary.GetMovies\",%20\"params\":%20{%20\"filter\":%20{\"field\":%20\"playcount\",%20\"operator\":%20\"is\",%20\"value\":%20\"0\"},%20\"limits\":%20{%20\"start\"%20:%200,%20\"end\":%2075%20},%20\"properties\"%20:%20[\"art\",%20\"rating\",%20\"thumbnail\",%20\"playcount\",%20\"file\"],%20\"sort\":%20{%20\"order\":%20\"ascending\",%20\"method\":%20\"label\",%20\"ignorearticle\":%20true%20}%20},%20\"id\":%20\"libMovies\"}";
NSLog(#"%# ",sampleUrl);
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:sampleUrl]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
but I get an error saying that:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
When I copy my url in my browser: it works!
but not when I tried with xcode
I tried changing the setting "by 22% and eliminating \ : does not work!
how do I proceed?
thanks
The problem is that the string in sampleUrl is not a well formed URL (see RFC 1738).
It contains various characters that are not allowed in URLs, for example { and ". These character have to be percent-escaped before converting to an NSURL.
Where does your URL string really come from?
here is the result that works wonders:
NSString *urlString = [NSString stringWithFormat:#"http://xbmc:xbmc#192.168.1.23:8080/jsonrpc?request={\"jsonrpc\": \"2.0\", \"method\": \"VideoLibrary.GetMovies\", \"params\": { \"filter\": {\"field\": \"playcount\", \"operator\": \"is\", \"value\": \"0\"}, \"limits\": { \"start\" : 0, \"end\": 75 }, \"properties\" : [\"art\", \"rating\", \"thumbnail\", \"playcount\", \"file\"], \"sort\": { \"order\": \"ascending\", \"method\": \"label\", \"ignorearticle\": true } }, \"id\": \"libMovies\"}"];
NSLog(#"%# ",sampleUrl);
NSString *encodedUrl = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSURL *url = [[NSURL alloc] initWithString:encodedUrl];
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:encodedUrl]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
Thank you to you all for the help;)

access NSMutableDictionary value without key?

quite new to iOS development and objective-c at the same time. I have the following method:
-(NSMutableArray *)fetchDatabaseJSON{
NSURL *url = [NSURL URLWithString:#"http://www.ios.com/ios/responseScript.php"];
NSError *error = nil;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:&error];
//jsonArray = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
//NSLog(#"Array: %#",[jsonArray objectAtIndex:0]);
jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSLog(#"Dictionary: %#", jsonDictionary);
return jsonArray;
}
Now the NSLog shows this:
2013-02-03 19:15:37.081 TestConnection[24510:c07] Dictionary: (
Bannana,
Apple,
SomeCheese )
From what I understand that whatever is inside the dictionary doesn't have key-value. How can this be? and how can I fix it? I want to be able to have keys to ease operations on dictionary.
Regards,
JSONObjectWithData may return an NSArray or NSDictionary, depending on the JSON data you give it. If your JSON string is an array, you will have an NSArray. If your JSON data is a dictionary, you will get an NSDictionary.
Convert your JSON data (your data variable) to string and print it out with NSLog. To convert NSData to NSString, use something like:
NSString *myString = [[NSString alloc] initWithData:myData encoding:NSUTF8StringEncoding];
If you print it out and see a JSON array, you simply don't have a dictionary there.. If you can alter the server-code that generates the JSON, you may be able to change that.
One more thing I noticed, you assume that the returning container is mutable. If I'm not mistaken, you need to use an option like NSJSONReadingMutableContainers in the options parameter of JSONObjectWithData to get that.
One last tip, if you want to check in code if you have an NSArray (or NSDictionary), use something like:
if ([obj isKindOfClass:[NSArray class]]) {...}

Resources