How do you pass a list of words that are in xml format to a "core data" database?
And from that, each time your application loads how do you check to see if that database is up to date?
You will need to parse the incoming XML as string. If you are on a mac use NSXMLDocument... try something like this:
NSString *yourXML = #""; // replace with your xml as nsstring
NSError *error;
NSXMLDocument *xmlDoc = [[NSXMLDocument alloc] initWithXMLString:yourXML options:0 error:&error];
if (error) NSLog(#"Error parsing xml: %#", [error description]);
And then you could parse every item you are interested in using an XPath query like this:
NSArray *items = [xmlDoc nodesForXPath:#"//yourItem" error:&error];
And then you could likewise loop every single item for its properties in xml format.
Then fetch an item according to one or more key properties you have in your xml and check if they are already there.
I suggest you take a look at this post http://objectivesheep.com/archive/core-data-active-record-sheepdata/ for an easier way to manage your core data objects. In that case you would simply have something like:
if ([YourManagedObject checkIfEntityExistsWhereProperty:#"yourKeyProperty" equalsValue:keyValueFromXML]) ....
Hope this helps.
Related
I'm trying to parse the JSON file at this URL: http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22MSFT%22)%0A%09%09&format=json&diagnostics=true&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback=results
The code that I have so far is as follows:
NSData *data=[NSData dataWithContentsOfURL:[[NSURL alloc] initWithString:url]];
NSError *error = nil;
id myJSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#", error);
NSArray *jsonArray = (NSArray *)myJSON;
for (id element in jsonArray) {
NSLog(#"Element: %#", [element description]);
}
This code seems to come up with an error each time (ERROR 3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.)").
I'm wondering if this is a problem with the way that I'm downloading/parsing the data or if it's a problem within the actual JSON in which I have to approach it in a different matter.
Remove the &callback=results at the end of the URL. This causes the JSON to not start with an array or dictionary. Just be aware that if you are referencing "results" in your JSON code then you will need to remove/change that. If you diff the two JSON texts then you will see the difference (look at the beginning).
in a web browser open the result of the url you posted copy the contents then go to jsonlint.com and paste the contents then click validate. it shows you that the input is not valid json so you might have to do some additional parsing.
i have an app which fetches JSON response from server. the JSON response from server looks as follows:
{"status":"SUCCESS","message":"XYZ","token":"ABCDEFGHIJ"}
now i need to store this in a NSDictionary for further parsing. so i use the following approach:
urldata1=[NSURLConnection sendSynchronousRequest:theRequest returningResponse:&res error:nil]; NSDictionary
*myDictionary=[NSJSONSerialization JSONObjectWithData:urldata1 options:NSJSONReadingMutableContainers error:nil];
}
but now the dictionary i get looks as follows:
{
message = "XYZ";
status = SUCCESS;
token = "ABCDEFGHIJ";
}
So i see that the dictionary has been sorted on the basis of keys... is there a way to reproduce the exact same response from server in my dictionary..
It doesn't matter in what order the NSDictionary is because you retrieve the object from the dictionary with keys.
So if you want to access the status first use this code
NSString *status = [myDictionary objectForKey#"status"];
NSString *message = [myDictionary objectForKey#"message"];
NSString *token = [myDictionary objectForKey#"token"];
And you can access a Dictionary inside a Dictionary like this
NSDictionary *dict= [myDictionary objectForKey#"SomeOtherDictionary"];
Sorting a dictionary is meaningless. You need to first create an array which will sort according to your needs.
You can refer Sorting NSDictionary from JSON for UITableView for further explanations.
Hey every one i am programming an iphone app to get google search results into my app ,,, i have used the JSON Class to get the result ... when i parsed it in JSON Parser and store it in NSDictionary i got 3 keys :
responseData
responseDetails
responseStatus
the important one is the first one responseData which is has the search results ...
the problem that there is (i think) another key within responseData which is "results" which contains the urls and other stuffs which is the most important part for my app... how to access this one and put it into NSDictionary .....
this is the request :
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton
and to make things clear please consider to put that request into your browser and when you get the results copy it and put it in this website at the left side to see what the keys and other things:
http://json.parser.online.fr/
thnx
You could use JSON parser - SB Json to convert json string into ObjectiveC objects. Note that there are a number of JSON parsers available in ObjectiveC but I chose SB Json for it's ease of usage. But according to some benchmarks JSONKit is faster than SBJson.
Once you have your json string use this like so -
#import "JSON.h"
// Create SBJSON object to parse JSON
SBJSON *parser = [[SBJSON alloc] init];
// parse the JSON string into an object - assuming json_string is a NSString of JSON data
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSLog(#"JSON data: %#", object);
Here's what you would do if you needed to parse public timeline from Twitter as JSON.The same logic could be applied to your Google Search results. You need to carefully inspect your json structure that's all...
// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.json"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(#"%# - %#", [status objectForKey:#"text"], [[status objectForKey:#"user"] objectForKey:#"screen_name"]);
}
Il me semble que vous savez déjà comment analyser JSON en forme NSDictionary, alors voici quelques suggestions sur la façon de forer vers le bas pour vos résultats détaillés en cascade. En anglais pour tout le monde.
responseData itself is an NSDictionary and results is an object within it. Results happens to be an array for the case you gave.
After you convert the JSON to NSDictionary form, you will have recursively converted all of the objects inside.
You might try something like this to get at what you are looking for:
Lets assume the the fully converted JSON is in a NSDictionary called response
NSDictionary *responseDate = [response objectForKey:#"responseData"];
NSArray *resultsArray = [responseData objectForKey:#"results"];
Now you can use an iterator or a for-loop to go through each result.
One word of caution is that if there is only one result, you should first test to see if the class of the object is NSArray. Also, if there are no results, you should test for that too.
So you may want to code it this way to handle these cases:
NSDictionary *responseDate = [response objectForKey:#"responseData"];
If ([[responseData objectForKey:#"results"] isKindOfClass [NSArray class]]) {
NSArray *resultsArray = [responseData objectForKey:#"results"];
... do other things to get to each result in the array ...
}
else if ([[responseData objectForKey:#"results"] isKindOfClass [NSDictionary class]]) {
// it looks like each individual result in returned in a NSDictionary in your example
... do the things to handle the single result ...
}
else {
// handle no results returned
}
The first thing you should do, if you do not understand exactly what's going on, is to NSLog the description of the JSON parser output. This will be a "nest" of NSDictionary and NSArray, and when you see the description output you will understand that there is a one-to-one mapping of JSON "object" to NSDictionary and JSON "array" to NSArray. So you "understand" the parser output the same way you "understand" the JSON source.
In your case you'd likely extract the "responseData" object, cast it to an NSDictionary, extract "results" from that, cast it (guessing here) to an NSArray, then iterate through that array to extract your individual results.
I am implementing a client based application. In that I have an xml string. I need to convert it to JSON format and send to the server. I have no idea on converting this. Can you guys please suggest me any documentation or idea to this?
Step #1: Read XML into NSDictionary: http://troybrant.net/blog/2010/09/simple-xml-to-nsdictionary-converter/
Step #2: Convert NSDictionary into JSON: http://code.google.com/p/json-framework/
As Steve said the two steps are those, I leave you a bit of code, maybe can help you a bit more:
// Don't forget the imports ;)
#import "XMLReader.h"
// You must have a XML string from somewhere
NSString XMLString = yourXML;
// I remove all returns and tabs from the text, after i would be annoying if you don't remove it
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"\r" withString:#""];
XMLString = [XMLString stringByReplacingOccurrencesOfString:#"\t" withString:#""];
// Parse the XML into a dictionary
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:XMLString error:&parseError];
NSError *error;
self.dataParsed = [NSJSONSerialization dataWithJSONObject:xmlDictionary
options: NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
// Print the dictionary
NSLog(#"%#", xmlDictionary);
Right now I have an NSArray whose items are just written in the implementation file.
I'd like to know how to make it so I can store all the items on a web (text) file. Example:
http://mysite.com/files/objects.txt
On that document:
Object 0 goes here
Object 1 goes here
Object 2 goes here
Object 3 goes here
etc. All separated by a line break.
How would I be able to do this? And when I update that text file, I'd like the objects to update as well. I'd do this via an NSMutable array, correct?
Thanks in advance.
- (NSArray*)getObjectsFromWeb {
NSURL *url = [NSURL URLWithString:#"http://mysite.com/files/objects.txt"];
NSStringEncoding usedEncoding;
NSError *error;
NSString *data = [NSString stringWithContentsOfURL:url
usedEncoding:&usedEncoding
error:&error];
return [data componentsSeparatedByString:#"\n"];
}
after data is assigned here, usedEncoding (and possibly error) will have a value that you can inspect and tak action on if you like.