31580

Convert NSDictionary To JSON

Question:

<strong>How to Convert NSDictionary into JSON ?</strong>

I have posted a dictionary into server using json. And in the time receiving the data from the server using GET method. the data cant be accessed using normal key calling method like

_secretanswer.text=[[NSString alloc]initWithFormat:@"%@",[customfield objectForKey:@"secanswer"]];

the server returning a NCFString as the result.

How to convert and post a NSDictionary in the JSON format?

Answer1:

NSError * error; NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&error]; NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]

Answer2:

I believe that what you're looking for is NSJSONSerialization.

This answer assumes use of NSURLConnection's block based API to execute your GET.

[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { if (data) { NSError *jsonError = nil; NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError]; if (dict) { // You got a valid NSDictionary out of your JSON response. NSLog(@"my returned dictionary: %@", dict); } else if (jsonError) { // JSON data could not be parsed into NSDictionary. Handle as appropriate for your application. return; } } else if (connectionError) { // Handle connection error } }];

But even if you're using dataWithContentsOfURL:, the point is the same. Feed your data in to NSJSONSerialization's + jsonObjectWithData:options:error: method, check if you get a dictionary back from that, and proceed.

EDIT: If you're looking to create a JSON post body for an HTTP request from an NSDictionary, NSJSONSerialization has you covered there as well.

NSError *error = nil; NSData *data = [NSJSONSerialization dataWithJSONObject:someDictionary options:NSJSONWritingPrettyPrinted error:&error]; if (data) { // You got your data. NSLog(@"my data: %@", data); [someURLRequest setHTTPBody:data]; } else if (error) { NSLog(@"error: %@", [error localizedDescription]); }

Recommend

  • Navigate user to New Screen on listitem click React native
  • How to change the Assemby and the Object type on the Newtonsoft.Json serialization/deserialization?
  • How do I observe a signal and immediately receive a `next` event if it has already occured?
  • Convert Tiff data type in libTiff to nsdata ios
  • Variable is not a static member of class
  • Java Parser Json as array multidimensional
  • Facebook iOS SDK v4.0, get friends list
  • Deleting in NSDocumentDirectory
  • How create UIImage from bytes?
  • Python list of (node_id, parent_node_id) to JSON
  • Error Domain=NSCocoaErrorDomain Code=3840 “Invalid value around character 0.” UserInfo={NSDebugDescr
  • C++ cout and enum representations
  • EntLib Way to Bind “Null” Value to Parameter
  • is there a way to update filter with async data
  • How do I Dispose a HttpResponseMessage in my Web Api Method?
  • DateTime.Today for a specific time zone
  • Doctrine/Symfony entity generator and generating entity from one table
  • Casting between Interfaces and Classes
  • jwtBearer bearer token with rc-1 update to ASP.Net 5
  • Enabling DTD support in Sql Server
  • Convert SQLite database to XML
  • WPF Visiblity Binding to Boolean Expression with multiple Variables
  • Conversion from string “a” to type 'Boolean' is not valid
  • Connect .sks to skscene.h
  • How can the INSERT … ON CONFLICT (id) DO UPDATE… syntax be used with a sequence ID?
  • WPF - CanExecute dosn't fire when raising Commands from a UserControl
  • Font Awesome Showing Box instead of Icons
  • Properly structure and highlight a GtkPopoverMenu using PyGObject
  • Arrays break string types in Julia
  • Free memory of cv::Mat loaded using FileStorage API
  • C# - Getting references of reference
  • Hits per day in Google Big Query
  • FormattedException instead of throw new Exception(string.Format(…)) in .NET
  • Memory offsets in inline assembly
  • Turn off referential integrity in Derby? is it possible?
  • Linking SubReports Without LinkChild/LinkMaster
  • Is it possible to post an object from jquery to bottle.py?
  • XCode 8, some methods disappeared ? ex: layoutAttributesClass() -> AnyClass
  • Python/Django TangoWithDjango Models and Databases
  • jQuery Masonry / Isotope and fluid images: Momentary overlap on window resize