How to get some values from json saved in nsstring? - iphone

My WS returns simple json like this:
{
"thumbnail_url": "http://something.com/photos/003/582/test-tiny.jpg?1321956139",
"success": true,
"photo_url": "http://something.com/photos/003/582/test-medium.jpg?1321956139",
"big_photo_url": "http://something.com/photos/003/582/test-big.jpg?1321956139"
}
I get this in NSData from NSURLConnection. I know how to make NSString from NSData. I would like to get value for "photo_url" key.
How can it do this?

You have to use SBJSON framework to get value of photo_url.
in SBJSON framework have one method that return NSMutableDictionary For String.
You can use like this [string JSONValue] that will return NSMutableDictionary.
After that use will be get value from this code [dict valueForKey:#"photo_url"]
Thanks,
MinuMaster

Use TouchJSON or SBJson parser to parse this.

For iOS 5 only you can use the built in NSJSONSerialization class.
If you need to support iOS4 then JSONKit is a good solution.
You can then query your results like a normal dictionary.

Related

Passing UIImage to JS using the native Trigger.IO API

I'm using an instance of ABAddressBookRef to access the ios address book. Ultimately I'd like to return a NSDictionary that contains names, phone numbers, and a thumbnail image. It's this last one that's giving me trouble. I can successfully include all the rest.
Here is just that UIImage being added to the dictionary contact with thumbnail as its key.
UIImage* contactThumbnail = [UIImage imageWithData:(__bridge NSData *)ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail)];
NSDictionary *contact = [NSDictionary dictionaryWithObjectsAndKeys:
contactThumbnail, #"thumbnail", nil];
According to the Trigger.IO Docs I'm allowed to return a NSString, NSNumber, NSDictionary or NSArray. How would I go about returning an image? Should I convert it, just point to it, what other options exist?
I've never worked with Trigger.IO, but I'll bet when they say you can use NSString, NSNumber, NSDictionary, or NSArray, they mean ONLY those classes. A dictionary that contains objects of types not on that list, such as UIImage, won't work. That's how JSON data serialization generally works.
The solution to that problem is to serialize the image, probably into Base64 data and include that Base64 string within the dictionary, instead of the image. You can then use a data: URL within your JavaScript to reconstruct the image.

Writing JSON using SBJSON

I have recently started parsing JSON documents using SBJSON Parser, and I am able to read JSON documents just fine. However I am unable to figure out how I am meant to write JSON using this library. Under the documentation
http://stig.github.com/json-framework/api/3.0/interfaceSBJsonStreamWriter.html
There is a class for writing JSON, but I cannot figure out how to use it. There are no tutorials in his documentation on how to use it, and I can't find any tutorials online about using it.
As an example, I tried doing something like this
SBJsonStreamWriter *write = [[SBJsonStreamWriter alloc]init];
[write writeObjectOpen];
[write writeString:#"Testing"];
[write writeObjectClose];
But I don't know how to print this out, and I need to be able to write JSON for my project as I will be updating JSON files, so need to understand how to write JSON.
As anyone used this library before to write? If so could you please show me a quick example of how it is done
Thanks in advance!
Note: I can't use the in built JSON Parser released with new xCode as my app must be able to support phones from IOS 4+ and the new Parser won't work on phones that do not have IOS 5 installed
EDIT
Example say I wanted to create a JSON file which consisted of an array of names e.g.
{
"name":[
"Elliot Jacobs",
"Paul",
"Maria",
"Richard",
"Ana"
]
}
EDIT 2:
Example two
{
"HomeScreen":{
"Title":{
"Name":"James Bond",
"Number":"07789 123 456"
}
}
}
I'm not quite sure what you mean by 'writing JSON' so I assume that you need to construct a JSON-formatted string. Are you certain that you must use the stream writer? If not, here's an example with strings:
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSDictionary *command = [NSDictionary dictionaryWithObjectsAndKeys:
#"string1", #"key1",
#"string2", #"key2",
nil];
NSString *jsonCommand = [writer stringWithObject:command]; // this string will contain the JSON-encoded command NSDictionary

Parse XML in iPhone (attributed not separated)

Is there a way to parse an XML in iOS where the attribute are not separated
e.g:
Users
UserId="1" Name="John Smith" Loc="London"
UserId="2" Name="Johnny Cash" Loc="Nashville"
Users
Thanks
It seams like you havent got xml at all. You are missing all usefully symbols that would normally help with the parsing. You taks is to parse a new format specification.
My first bit of advice is to ask whoever is providing you with this feed to put it into a proper format (JSON or plist are the easiest to work with).
Failing this, if the feed is not too big (otherwise you will hit performance issues), parse the feed manually character by character. You probably want to write a event based parser.
Split the feed line by line, perhaps using componentsSeparatedByString:
Then read characters into a string untill you hit an = that string is your key. Next read between the quotes "" That string is your value. FIre the key and the value off to a delegate.
JSON parsing classes will help you out...
NSString *responseString = #""; // your data contained string.
SBJSON *json = [[SBJSON new] autorelease];
NSArray *resultData = [json objectWithString:responseString error:&error];

Sending array through email on iphone

Hey guys I need to send the content of an NSMutableArray through email. I have a mailing function but I'm not sure on how to place the content of the array into a NSString to be displayed on the email under each other. Is there a way to place all the content of the array into the string with maybe HTML nextline command between each array element?
NSString *emailBody = #"Need to put the body here";
Thanks
I'll suggest you convert your array into a text string using JSON. Then place the text in the email, send it away and use JSON on the receiving end to reconstruct the array.
You can get an iPhone version of JSON called TouchJSON here.
Claus
This process is known as serialization. Apple has a guide for it, that's worth reading through.
The simplest way is to call the array's description method which will return a human readable plist in a NSString.
If you need to reconstitute the array from the email. You will need save the array as xml plist using the writeToFile: method. Then read the file back in as a string. To reconstitute you will need to extract the xml from the email, put it in a NSString, write that to file, then read it back into an NSArray.
(IIRC, there used to be a way to write to NSString as if it was a file but I can't remember how to do it anymore. Probably, writing to a NSFileHandle and reading it back instantly.)
Edit:
Can you please explain more on the
array's description method please.
Like so:
NSArray *myArray=[NSArray arrayWithObjects:#"Obj1",#"Obj2",#"Obj3",nil];
NSLog(#"myArray=%#",[myArray description]);
...prints:
myArray=(
Obj1,
Obj2,
Obj3
)
For your project you can do:
NSString *arrayString=[myArray description];
The is also a descriptionWithLocale that will print the array in different languages. I don't have a ready example for that. See NSArray, NSLocale and The Locales Programming Guide

get element value

I have a NSString like that? (in iPhone application)
NSString *xmlStr = "<?xml version=1.0 encoding=UTF-8>
<information>
<name>John</name>
<id>435346534</id>
<phone>045635456</phone>
<address>New York</address>
</information>"
How I can get elements value?
(Do i need convert to XML format and get elements value? or split string? any way please tell me?)
Thank you guys.
If you want to use split string, you can use tokenization of strings using "componentsSeparatedByString" method. This is a more cumbersome method of course, rather than the recommended XMLParser
To get the name.
NSArray *xmlStr_first_array = [xmlStr componentsSeparatedByString: #"<name>"];
NSString *xmlStr_split = [NSString stringWithFormat:#"%#",[xmlStr_first_array objectAtIndex:1]];
NSArray *xmlStr_second_array = [xmlStr_split componentsSeparatedByString: #"</name>"];
NSString *name = [NSString stringWithFormat:#"%#",[xmlStr_second_array objectAtIndex:0]];
The most obvious solution is to use an XML parser to retrieve the values from each element.
You could use the excellent TBXML for this task. It provides a really simple interface where it wouldn't take more than a few lines to retrieve the desired values. The drawback to using this small library is that it (as far as I know) loads the entire XML data into memory. In this particular case, however, that is not problem at all.
There's of course also the option of using the NSXMLParser, though this is an event-driven parser, and thus a bit less simple to use.
Your string is in xml format already and you need to parse it to retrieve data. There're several options available - for example you can use NSXMLParser class or libxml library.
Edit: XMLPerformance sample project shows how to use both approaches and compare their performance.