I am trying to make a google reader app. I am able to get the subscription list in JSON format like this:
{"subscriptions":[{"id":"feed/http://aspn.activestate.com/ASPN/Cookbook/Python/index_rss","title":"ActiveState Code: Python recipes","categories":[{"id":"user/014533032765194560dwd0/label/Programming","label":"Programming"}],"sortid":"E6312EFB","firstitemmsec":"1258141669516","htmlUrl":"http://code.activestate.com/recipes/langs/python/"},
I am interested in getting the label value (in the above case "Programming") into an array. Here is my current code:
-(BOOL)parsedSuccess {
SBJsonParser *parser = [[SBJsonParser alloc]init];
if (!receivedData) {
[self getSubscriptionList:GOOGLE_READER_SUBSCRIPTION_LIST];
}
NSMutableString *body = [[NSMutableString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding];
if (body) {
NSArray *feeds = [parser objectWithString:body error:nil];
NSDictionary *results = [body JSONValue];
NSArray *subs = [results valueForKey:#"subscriptions"];
NSString *subTitles;
for (NSDictionary *title in subs){
subTitles = [title objectForKey:#"categories"];
NSLog(#"%#",subTitles);
}
}
return YES;
}
Can someone help me in getting the label values?
[[[[[result valueforkey:#"subscription"]objectatindex:0]valueforkey:#"categories"]objectatindex:intvalue]valueforkey:#"label"];
I just helped to make logic. Be sure to check for spelling mistakes before implementing.
Related
My json response data formate as :-
[{"0":"1","id":"1","1":"Pradeep","name":"Pradeep","2":null,"sender":null,"3":null,"
So to parse the "name" on table view?
My own implementation is:-
I am new in ios development please help me
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData
options:0 error:nil]; // response saved in allDataDictionary
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"]; // feeds entry
NSArray *feedforentry=[feed objectForKey:#"entry"];
for(NSDictionary *diction in feedforentry)
{
NSDictionary *title=[diction objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self JustConfesstable]reloadData]; // reload table
}
First of all get data in Dictionary and then store what you want in NSArray.. using Keys
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(#"%#",json);
NSLog(#"%#",delegate.firstArray);
NSArray * responseArr = json[#"Deviceinfo"];
NSArray * firstarray=[[NSArray alloc]init];
for(NSDictionary * dict in responseArr)
{
[firstarray addObject:[dict valueForKey:#"name"]];
}
first array contains names.. what you want from that json response.
and then pass that data to tablview. what you want to do here you get the array of name data.
You need to use JSON parser. I will recommend: https://github.com/johnezang/JSONKit
With that you can do:
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSError *error = nil;
id objectFromJson = [jsonKitDecoder objectWithData:data error:&error];
I have an application in which I am having a json response like this.
{"success":"true","message":"You have logged in","pserial":"1"} and I am separating with ":".
And I am getting data like this pSerial:"1"} but I want only 1 value.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSString *approvalString = [[strResp componentsSeparatedByString:#":"] objectAtIndex:3];
NSLog(#"pSerial:%#",approvalString);
for Example :
SBJsonParser *jsonPar = [[SBJsonParser alloc] init];
NSError *error = nil;
NSArray *jsonObj = [jsonPar objectWithString:jsonString error:&error];
id jsonObj = [jsonPar objectWithString:jsonString error:&error];
if ([jsonObj isKindOfClass:[NSDictionary class]])
// treat as a dictionary, or reassign to a dictionary ivar
else if ([jsonObj isKindOfClass:[NSArray class]])
// treat as an array or reassign to an array ivar.
Then get the value :
NSMutableArrary *userMutArr = [NSMutableArray array];
for (NSDictionary *dict in jsonObj)
{
User *userObj = [[[User alloc] init] autorelease];
[userObj setFirstName:[dict objectForKey:#"firstName"]];
[userObj setLastName:[dict objectForKey:#"lastName"]];
[userObj setAge:[[dict objectForKey:#"age"] intValue]];
[userObj setAddress:[dict objectForKey:#"address"]];
[userObj setPhoneNumbers:[dict objectForKey:#"phoneNumber"]];
[userMutArr addObject:userObj];
}
Hope you will understand. and read some Documents. it will help you.
It looks like you are in need of JSON Parsing. Here, what you want is JSON Parsing, not separating data from the JSON Response. JSON is the format of the data in which data is formatted in Key-Value pairs. You can fetch the "Value" of any object using the "Key".
Your first two lines are correct.
NSURL *url = [NSURL URLWithString:strUrl];
NSData *respData = [NSData dataWithContentsOfURL:url];
Now, you can parse JSON Response like this :
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&error];
NSString *pSerial = [json objectForKey:#"pserial"];
This will give you the value of "pserial" from your response. Similarly, you can get the values for "success" and "message". You can check it using this line :
NSLog(#"pserial :: %#",pserial);
You need to parse the JSON Response String, you can use any JSON parser like:
https://github.com/stig/json-framework/
And in your code do:
NSString *strResp = [[NSString alloc]initWithData:respData encoding:NSUTF8StringEncoding];
NSDictionary *ResponseDictionary = [strResp JSONValue];
NSString * pSerial = (NSString*)[ResponseDictionary objectForKey:#"pserial"];
Dont separation by ":" just use JSONValue your response is like
// {"success":"true","message":"You have logged in","pserial":"1"}
// with SBJsonParser parse your object like this
NSDictionary *responseJson = [YOUR-OBJECT JSONValue];
Note: dont forget to add Json header file
Its better you use any OpenSource Json Parser
Here is a stack post Comparison of different Json Parser for iOS
I have a very simple xml file by name options.xml
<Dat>
<Name>Tom</Name>
<Option>1</Option>
</Dat>
Using NSXML I am trying to change "Tom" to "Jim" and save the file. How can I do that. I read many document and there is no straight forward solution. Can some one help me with the code ?
update: I ended up in trying with Gdatasxml
-(void)saveToXML
{
NSString* path = [[NSBundle mainBundle] pathForResource:#"options" ofType:#"xml"];
NSData *xmlData = [[NSMutableData alloc] initWithContentsOfFile:path];
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:xmlData options:0 error:&error];
GDataXMLElement *rootElement = [GDataXMLElement elementWithName:#"Dat"];
NSArray *mySettings = [doc.rootElement elementsForName:#"Dat"];
for (GDataXMLElement *mySet in mySettings)
{
NSString *name;
NSArray *names = [mySet elementsForName:#"Name"];
if (names.count > 0)
{
GDataXMLElement *childElement = (GDataXMLElement *) [names objectAtIndex:0];
name = childElement.stringValue;
NSLog(childElement.stringValue);
[childElement setStringValue:#"Jim"];
}
}
[xmlData writeToFile:path atomically:YES];
}
But this is not saving the data. Help.
Editing XML is a little difficult in iOS. You need to parse the original xml to a model and then form the xml.
You can make use of 3rd party library such as GDataXML for forming XML from a data source.
//Edited user info saved in a dictionary
NSDictionary *dictionary = #{#"Name": #"Jim", #"Option":#"1"};
GDataXMLElement *rootElement = [GDataXMLElement elementWithName:#"Dat"];
[dictionary enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
GDataXMLElement *element = [GDataXMLElement elementWithName:key stringValue:obj];
[rootElement addChild:element];
}];
//xml document is formed
GDataXMLDocument *document = [[GDataXMLDocument alloc]
initWithRootElement:rootElement];
NSData *xmlData = document.XMLData;
NSString *filePath = [self savedXMLPath];
//XML Data is written back to a filePath
[xmlData writeToFile:filePath atomically:YES];
Create a class that is essentially an XML "node". Then in your parser setup a system of these XML nodes in the same fashion as you read them. Then search through that body and find the element that you would like to change. Change it. Then write a function that goes through these "node" objects and writes a new NSString in XML format and save that string to file. There is no real easy way that I know of to write XML files. I'm sure someone has a library out there to do it, but I had very complex XML's to deal with so I wrote my own. If you would like specific code let me know and I can try to give you parts of what you may need.
You Can use GDATAXML for changing XML node
Here is Working Code snippet
NSString *XMLString = #"<Dat><Name>Tom</Name><Option>1</Option></Dat>";
NSError *error = nil;
GDataXMLElement *newElement = [[GDataXMLElement alloc] initWithXMLString: XMLString error: &error];
NSLog(#"New element: %# error: %#", newElement, error);
if(nil == error)
{
GDataXMLElement *childElement = [[newElement elementsForName: #"Name"] objectAtIndex: 0];
[childElement setStringValue:#"Jim"];
childElement = [[newElement elementsForName: #"Option"] objectAtIndex: 0];
[childElement setStringValue:#"2"];
}
NSLog(#"New element now: %#", newElement);
Check by using this code snippet
Im facing some problem with json and objective c. Atm i am using sbJson framework (i can change framework if some tell me do it!) and im not being able to parse a json array.
this is the json i want to parse,
{"JsonEventosResult":
[
{"nombre":"Venta de Reposición N°13","id":34,"fecha":"16/09/2011"},
{"nombre":"evento rose","id":37,"fecha":"04/10/2011"},
{"nombre":"Prueba PhoneGap","id":40,"fecha":"23/11/2011"}
]
}
this is my code on iphone:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSArray *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];
if (luckyNumbers == nil)
label.text = [NSString stringWithFormat:#"JSON parsing failed: %#", [error localizedDescription]];
else {
NSMutableString *text = [NSMutableString stringWithString:#"Lucky numbers:\n"];
for (int i = 0; i < [luckyNumbers count]; i++)
[text appendFormat:#"%#\n", [luckyNumbers objectAtIndex:i]];
label.text = text;
}
}
the error i get is that luckyNumbers is an array with 0 object.
the sample i got if from http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/ .
so where is the problem? the json i get form service or the framework ?
thx
You're handling it wrong. It's not an array, it's a dictionary, the value for key #"JsonEventosResult" is the array. So In your JSON objectwithstring line, make that an nsdictionary and then point to that key
OR remove the {"JsonEventosResult": and final } so that it already is an array
Oh, and I think you'll have to Unicode escape your accented characters and degree symbol (test your JSON at jsonlint.org to make sure it's valid)
I have the following response from server side:
{"_playLists":[{"name":"Playlist 1","items":[{"name":"Poza 1","target":"http:\/\/myaudi.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic1_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic1_iphone3_thumb.jpg"},{"name":"Poza 2","target":"http:\/\/audifrance.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic2_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic2_iphone3_thumb.jpg"}]},{"name":"Playlist 2","items":[{"name":"Poza 3","target":"http:\/\/google.ro","url":null,"url_thumb":null}]}]}
And I'm trying to acces this by using:
SBJSON *parser = [[SBJSON alloc] init];
NSString *responseString = [request responseString];
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
But I get EXC_BAD_ACCESS at this line
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
saying variable json_string is not a CFString.
Can someone help me solve this and tell me how to act further to acces the JSON components?Thank you:)
EDIT:
{
items = (
{
name = "Poza 1";
target = "http://myaudi.fr";
url = "http://test.res-novae.fr/sfrplay/upload/image/pic1_iphone3.jpg";
"url_thumb" = "http://test.res-novae.fr/sfrplay/upload/thumb/pic1_iphone3_thumb.jpg";
},
{
name = "Poza 2";
target = "http://audifrance.fr";
url = "http://test.res-novae.fr/sfrplay/upload/image/pic2_iphone3.jpg";
"url_thumb" = "http://test.res-novae.fr/sfrplay/upload/thumb/pic2_iphone3_thumb.jpg";
}
);
name = "Playlist 1";
},
{
items = (
{
name = "Poza 3";
target = "http://google.ro";
url = "<null>";
"url_thumb" = "<null>";
}
);
name = "Playlist 2";
}
You should use one of the JSON frameworks available out there, i.e. JSONKit or json-framework, which both makes it really easy to convert strings to JSON objects (i.e. an NSDictionary).
If you're using json-framework, you'd only have to do the following (if you've included JSON.h):
NSDictionary *jsonObject = [responseString JSONValue];
There is a issue with your line
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
you have declared responseString as NSString *responseString = [request responseString];
and you are giving it as Data while allocating json_string
You do not need this line
NSString *json_string = [[NSString alloc] initWithData:responseString encoding:NSUTF8StringEncoding];
responseString is already a string (and initWithData: expects a NSData object not NSString). Just feed it straight to the parser:
NSArray *statuses = [parser objectWithString:responseString error:nil];
Can someone help me solve this and tell me how to act further to acces
the JSON components?
You now have a nice NSArray of NSDictionary objects representing your JSON data, you can access the first item, represented by
{"name":"Playlist 1","items":[{"name":"Poza 1","target":"http:\/\/myaudi.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic1_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic1_iphone3_thumb.jpg"},{"name":"Poza 2","target":"http:\/\/audifrance.fr","url":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/image\/pic2_iphone3.jpg","url_thumb":"http:\/\/test.res-novae.fr\/sfrplay\/upload\/thumb\/pic2_iphone3_thumb.jpg"}]}
by getting the first element in the array
NSDictionary* dict = [statuses objectAtIndex:0];
and the keys in the dictionary should be "name", and "items". The object for "name" will be an NSString and the object for "items" will be an NSArray containing further NSDictionary objects describing each item.