how to implements code for get the JSON objects in iphone? - iphone

hi all i am a new iphone developer. i am getting response from my required URL as shown in the below here i need to get Name of "CategoryID":1 and Name of "CategoryID":2 both are in separate array sets. how to implements code for get the JSON objects in iphone?. thank you
code for getting response:
theXML = [[NSString alloc] initWithBytes: [RoutData mutableBytes] length:[RoutData length] encoding:NSUTF8StringEncoding];
NSLog(#"---->>>>>>-->>>:%#",theXML);
Response:
LocationTracking[1807:f803] ---->>>>>>-->>>:<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><getGearLockerCategoriesResponse xmlns="http://tempuri.org/"><getGearLockerCategoriesResult><status>SUCCESS</status><errorType /><errorMessage /><jsonString>[{"CategoryID":1,"ItemCount":1,"level":1,"Name":"Boots","Description":"Boots descrition","childs":[{"CategoryID":2,"ItemCount":1,"level":2,"Name":"Cold Water","Description":"Cold Water Description","childs":[]}]}]</jsonString><serverTimestamp>63477507673796</serverTimestamp></getGearLockerCategoriesResult></getGearLockerCategoriesResponse></soap:Body></soap:Envelope>
<jsonString>
[{"CategoryID":1,"ItemCount":1,"level":1,"Name":"Boots","Description":"Boots
descrition","childs":[{"CategoryID":2,"ItemCount":1,"level":2,"Name":"Cold
Water","Description":"Cold Water Description","childs":[]}]}]
</jsonString>
<serverTimestamp>63477390375625</serverTimestamp>
</DiveTravelerResponse>

The Touch JSON library is a good solution: https://github.com/TouchCode/TouchJSON

NSJSONSerialization. If your JSON is in an NSString named 'str':
NSError *jsonError = nil;
NSArray *rootObjectArray = [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&jsonError];
if (rootObjectArray)
{
/* you have a foundation object */
}
else
{
/* something went wrong */
NSLog(#"jsonError: %#", [jsonError localizedDescription]);
}

Related

iphone with sbjson framework cant parse json array

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)

Can't parse xml with touch xml

I'm quite new to programing and have a problem. I have been using touchxml for parsing and there hasn't been any problem before. Now i want to parse an xml string.
I've looked all over the internet but can't find the answer.(i've never done initWithXMLString before maybe i'm doing something wrong here?)
My current code for parsing:
NSArray *resultNodes = NULL;
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithXMLString:str options:0 error:nil];
NSString *strName;
resultNodes = [rssParser nodesForXPath:#"//FictionBook" error:nil];
NSLog(#"RESULT NODE COUNT =%d",[resultNodes count]);
and my string looks like this:
"<?xml version="1.0" encoding="UTF-8"?>
<FictionBook xmlns="http://www.gribuser.ru/xml/fictionbook/2.0" xmlns:l="http://www.w3.org/1999/xlink"><description><title-info><genre>prose_contemporary</genre> <author><first-name>Мария</first-name><last-name>Метлицкая</last-name><id>f97cbf85-bb7c-102b-8639-bb1d5f8374bd</id></author><book-title>Наша маленькая жизнь (сборник)</book-title> <annotation><p>Мария Метлицкая рассказывает о простых людях – они не летают в космос, не блистают на подмостках сцены, их не найдешь в списке Forbеs.</p></annotation></description></title-info></FictionBook>"
xml apears to be valid, I've checked about 10 xml validators.
But i get 0 from [resultNodes count].
Anybody encountered something similar before?
Thanks in advance!
Try to check if there were an error while parsing:
NSError *error;
NSArray *resultNodes = NULL;
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithXMLString:str options:0 error:&error];
NSLog("Error: %#",error);
Also does your XML contains elements with namespaces?
Firstly get you xml validate or not by this http://www.xmlvalidation.com/ and if it validated then you are not getting any response then you should check the error code what the error is thrown by the xml parser and then try to check by error code what is the problem.

Parsing XML on iPhone with GDataXML

Ugh, I'm having a dickens of a time parsing xml from Exchange Web Services. I want to get the ItemID Id=xyz attribute (AAATAG...). Here is the XML:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Header><t:ServerVersionInfo xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" MajorVersion="8" MinorVersion="3" MajorBuildNumber="137" MinorBuildNumber="0"/></soap:Header><soap:Body><m:FindItemResponse xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"><m:ResponseMessages><m:FindItemResponseMessage ResponseClass="Success"><m:ResponseCode>NoError</m:ResponseCode><m:RootFolder TotalItemsInView="1" IncludesLastItemInRange="true"><t:Items><t:CalendarItem><t:ItemId Id="AAATAGNvb3Blcm1qQG11b2hpby5lZHUARgAAAAAA+Q4xQgA/2kCus7bZbZddngcA8vxBsULRa0S+uFR566ChHwAAAB4BwgAABgoCL+IgvEaj+O0Bl9BG2AAQEOyJMwAA" ChangeKey="DwAAABYAAAAGCgIv4iC8RqP47QGX0EbYABARELYs"/><t:Organizer><t:Mailbox><t:Name>Cooper, Micah</t:Name></t:Mailbox></t:Organizer></t:CalendarItem></t:Items></m:RootFolder></m:FindItemResponseMessage></m:ResponseMessages></m:FindItemResponse></soap:Body></soap:Envelope>
I'm using GDataXML, and here is my code:
- (void)parseFeed:(GDataXMLElement *)doc entries:(NSMutableArray *)entries {
NSLog(#"%#", doc);
NSDictionary *namespaceMappings = [NSDictionary dictionaryWithObjectsAndKeys:#"http://schemas.microsoft.com/exchange/services/2006/messages", #"messages",
#"http://schemas.microsoft.com/exchange/services/2006/types",#"types", nil];
NSArray *items = [doc nodesForXPath:#"//types:CalendarItem" namespaces:namespaceMappings error:nil];
for (GDataXMLElement *item in items) {
NSLog(#"Item: %#", item.stringValue);
NSString *itemID = [[item attributeForName:#"ItemId Id"] stringValue];
NSLog(#"itemID: %#", itemID);
}
}
I'm not pulling the item id -- in fact, it looks as if it is parsing at random places in the XML. Can anyone point me in the right direction? Thanks!

Parsing SOAP result using TouchXML in iOS SDK (iPad)

I'm working on an iPad project that is using functions in a WebService.
Handling webservice connection, data etc works find. But i'm not able to parse the result SOAP using TouchXML. Getting the nodes out of the xml always returns 0 length.
The output xml:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <soap:Body> <LogOnResponse xmlns="http://coreservices.org/v1"> <LogOnResult> <Id>1c0e9ad0-a3be-4cd0-8f0d-0616a63a4e28</Id> <userId>2</userId> <user> <ID>2 <Name>Beheerder <emailAddress /> <cultureName>nl-NL</cultureName> </user> </LogOnResult> </LogOnResponse> </soap:Body></soap:Envelope>
parser code:
NSData *aData = [[NSData alloc] initWithBytes:[webData mutableBytes] length:[webData length]];
NSString *xmlData = [[NSString alloc] initWithData:aData encoding:NSASCIIStringEncoding];
NSLog(#"%#", xmlData);
[xmlData release];
CXMLDocument *domUserIdentity = [[[CXMLDocument alloc] initWithData:aData options:0 error:nil] autorelease];
[aData release];
NSArray *nodesList = [domUserIdentity nodesForXPath:#"//LogOnResult" error:nil]; // 0 length
for (CXMLElement *resultElement in nodesList) {
for (int counter = 0; counter
NSString *elemName = [[resultElement childAtIndex:counter] name];
NSString * elemValue = [[[resultElement childAtIndex:counter] stringValue] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
[elemName release];
[elemValue release];
}
}
[nodesList release];
Any idea what did i do wrong?
Thank's alot in advance.
Inoel
Try using the NSXMLDocument, it should work as well as CXMLDocument. Here are some docs:
link
I recommend using an XPath Parser. You aren't doing anything too heavy, so the speed hit is well worth it. My personal choice is TFHpple. There are slightly faster and more precise solutions out there, but I find TFHpple's simplicity hard to beat.
Example:
NSData *data = [[NSData alloc] initWithContentsOfFile:#"example.html"];
// Create parser
xpathParser = [[TFHpple alloc] initWithXMLData:data];
NSArray *elements = [xpathParser search:#"//LogOnResult"];
TFHppleElement *element = [elements objectAtIndex:0];
// Get the text within the cell tag
NSString *content = [element content];
[xpathParser release];
[data release];
Obviously you'd have to write some code to save the parts you want. Looking at this data, I'd probably make a custom data holder class that you can access with properties. You can parse your XML into that and then save it as a property in the view controller that will be accessing it.
Happy coding!

TouchXML - CXMLDocument object failed to initialize

I am stuck with some TouchXML code. Please help.
I have the following code to get the data from an xml webservice:
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"String data: %# \n", data);
//Do the parsing
CXMLDocument *document = [[[CXMLDocument alloc] initWithData:urlData encoding:NSUTF8StringEncoding options:0 error:&error] autorelease];
NSLog (#"Document :%# \n",[document stringValue]);
The string data does have the content from the service, but how come the CXMLDocument object does not contain anything? Someone can tell me why?
2009-12-30 18:21:59.467 MyAdvancedBlog[3425:207] String data: <?xml version="1.0" encoding="utf-8"?>
<Post xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<IdPostazione>42</IdPostazione>
<StringID>HOANG</StringID>
<Name>CASSA2</Name>
<TerminalValid>true</TerminalValid>
<NeedSession>false</NeedSession>
</Post>
2009-12-30 18:21:59.469 MyAdvancedBlog[3425:207] Document :(null)
TouchXML's documentation says that CXMLDocument should act just like NSXMLDocument. So, the reference for initWithData:options:error: might help.
It says the result will be nil if it's unsuccessful, and error will then contain more info. Is it nil?
You might consider using NSXMLDocument for the moment, and see if they really do act the same. If they don't, file a bug with TouchXML.
You could also use initWithXMLString:options:error: along with that string you already decoded.
Edit: Even better. Here's example code for using NSXMLDocument. In theory, it should work for CXMLDocument as well.