I have a NSData object, i need to convert it a NSDictionary object.
NSData *data = ....;
Now i need to convert this to a NSDictionary, How can i do this programatically ?
note: After i save the NSData to the NSDictionary i should be able to access key value pairs of the NSDictionary.
I don't have a code to demonstrate my workings so far, I have only created the NSData object, and have no clue to continue :)
You can subclass MKNetworkOperation and override the responseJSON method with the following:
-(id) responseJSON
{
NSString *rawJSON;
id jsonValue = nil;
if ((rawJSON = [[NSString alloc] initWithData:[self responseData] encoding:NSUTF8StringEncoding]) != nil) {
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
if ((jsonValue = [jsonParser objectWithString:rawJSON]) == nil) {
NSLog(#"This string doesn't seem to be JSON: '%#'\nraw Data : '%s'", rawJSON, (char *)[[self responseData] bytes]);
return [self responseString];
}
}
else {
NSLog(#"This data doesn't seem to be an UTF8 encoded string: %#", [self responseData]);
return [self responseString];
}
return jsonValue;
}
Please check this link of stack overflow, I have already consumed the JSON services, it will help you a lot. All of the coding is there.
JSON Data Conversion
And here is the tutorial with sample project
JSON Parse Tutorial
Hope you would find it helpful
I highly recommend invoking SBJSON framework, it saved my time for many times, exactly finished my work and easily to use. You don't need to know the details of the conversion algorithm, just download and invoke it.
You might want to download it from here, then follow this tutorial to get your things done.
Related
Hi all so after a lot of hassle I managed to finally work my way around achieving and delimiting the JSON returned by Twitter Streaming APIs. How do i store the data returned by [NSJSONSerialization JSONObjectWithData:options:error:] into an array in appending
mode???
Here are the codes
To call the Streaming API
self.twitterConnection = [[NSURLConnection alloc] initWithRequest:signedReq delegate:self startImmediately: NO];
and in the delegate method (which is did receive data method)
NSError *parseError = nil;
self.dataSource=[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:&parseError];
What i want to do is to store this NSJSONSerialized output in a static Array(preferably in append mode) so that i can pass it to table view for display. how do i go about it?
Thanks in Advance
EDIT
`self.dataSource1=[[NSMutableArray alloc]init];
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
string = [NSString stringWithFormat:#"[%#]", [string
stringByReplacingOccurrencesOfString:#"\r\n" withString:#","]];
NSError *parseError = nil;
self.dataSource =[NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments|NSJSONReadingMutableContainers error:&parseError];
[self.dataSource1 addObjectsFromArray:self.dataSource];`
Use -[NSMutableArray addObjectsFromArray:] to add objects to a mutable array.
Based on your comment, it looks like you're recreating self.dataSource1 every time you get data in didReceiveData. You should only create the object once before sending the request.
I need read one webservice that return jsonarry in my iphone application.
After this reading, i will need make load this information in my tableview.
But the return is one string, how make transform this string in one format that my table view understand.
following example return
{"codUf":28,"descricao":"MG"},{"codUf":29,"descricao":"PR"},{"codUf":19,"descricao":"RJ"},{"codUf":25,"descricao":"SP"}]
Thanks !!
If you're using ios5, following the tutorial:
#define kBgQueue dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestKivaLoansURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
Now your JSON data should be in the json dictionary. Good luck and if you have further problems, do leave a comment.
i have a problem parsing my json data for my iPhone app, I am new to objective-C. I need to parse the json and get the values to proceed. Please help. This is my JSON data:
[{"projId":"5","projName":"AdtvWorld","projImg":"AdtvWorld.png","newFeedCount":"0"},{"projId":"1","projName":"Colabus","projImg":"Colabus.png","newFeedCount":"0"},{"projId":"38","projName":"Colabus Android","projImg":"ColabusIcon.jpg","newFeedCount":"0"},{"projId":"25","projName":"Colabus Internal Development","projImg":"icon.png","newFeedCount":"0"},{"projId":"26","projName":"Email Reply Test","projImg":"","newFeedCount":"0"},{"projId":"7","projName":"PLUS","projImg":"7plusSW.png","newFeedCount":"0"},{"projId":"8","projName":"Stridus Gmail Project","projImg":"scr4.png","newFeedCount":"0"}]
On iOS 5 or later you can use NSJSONSerialization. If you have your JSON data in a string you can do:
NSError *e = nil;
NSData *data = [stringData dataUsingEncoding:NSUTF8StringEncoding];
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
Edit To get a specific value:
NSDictionary *firstObject = [jsonArray objectAtIndex:0];
NSString *projectName = [firstObject objectForKey:#"projName"];
I would recommend using JSONKit library for parsing.
Here's a tutorial on how to use it.
You will basically end up with a dictionary and use objectForKey with your key to retrive the values.
JSONKit
or
NSJSONSerialization(iOS 5.0 or later)
I have had success using SBJson for reading and writing json.
Take a look at the documentation here and get an idea of how to use it.
Essentially, for parsing, you just give the string to the SBJsonParser and it returns a dictionary with an objectForKey function. For example, your code might look something like:
NSDictionary* parsed = [[[SBJsonParser alloc] init] objectWithString: json];
NSString* projId = [parsed objectForKey:#"projId"];
Use SBJson
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSMutableDictionary *dicRes = [parser objectWithString:stringFromServer error:nil];
No need to use third party classes. Objective-c already includes handling JSON.
The class NSJSONSerialization expects an NSData object or reads from a URL. The following was tested with your JSON string:
NSString *json; // contains your example with escaped quotes
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingAllowFragments error:&error]
For more options with NSJSONSerialization see the documentation.
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);
I am some NSStrings, and I am just joining them and making a single NSString, then I am converting that single NSString to NSData and sending via bluetooth to other iphone
but now I have to send image with above data,
how can I achieve such concept ?
but I want to send single NSData (UIImage+NSString), how can I ????
a tutorial on how to program Bluetooth data transfer on the iPhone is here:
http://www.devx.com/wireless/Article/43502/1954
The essential part you're looking for is here:
-(IBAction) btnSend:(id) sender
{
//---convert an NSString object to NSData---
NSData* data;
NSString *str = [NSString stringWithString:txtMessage.text];
data = [str dataUsingEncoding: NSASCIIStringEncoding];
[self mySendDataToPeers:data];
}
- (void) mySendDataToPeers:(NSData *) data
{
if (currentSession)
[self.currentSession sendDataToAllPeers:data
withDataMode:GKSendDataReliable
error:nil];
}
Good luck with it!
I would recommend sending them in separate packets since an image could be quite large (send the image itself in multiple packets). But if you really want to do it all at once, try wrapping them in an NSDictionary. Encode the dictionary into NSData, and send it off.
Something like the following would work.
NSDictionary *myDict = //whatever your dict should hold here...
NSMutableData *packet = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:packet];
[archiver encodeObject:myDict forKey:#"SomeKey"];
[archiver finishEncoding];