I am fairly new to xcode but I currently have an app that will send data to a sql database but I know it has to go through JSON first.
Say my app is simply a text box where a user enters a name and submits. How would I turn that data into JSON? What would the syntax look like?
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSJSONSerialization_Class/
If you are sending the data through a network, then look into AFNetworking.
(added in response to a comment)
NSString *jsonFromObject(id object)
{
NSError* error = nil;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject: object options: 0 error: &error];
if (error) {
NSLog(#"error creating json string: %#", error);
}
return [[NSString alloc] initWithData: jsonData encoding: NSASCIIStringEncoding];
}
Related
I'm trying to get data from Facebook, but I'm getting this error when I try to parse the data to a Dictionary:
Mistake: Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (No value.) UserInfo=0x144ad420
This is my code:
NSString *query =
#"SELECT page_id, type FROM page_fan WHERE uid = me() ";
// Set up the query parameter
NSDictionary *queryParam = #{ #"q": query };
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id results,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else {
BOOL can = [NSJSONSerialization isValidJSONObject:results];
NSLog(#"can %d", can);
NSError *mistake;
NSDictionary *first = [NSJSONSerialization JSONObjectWithData:results options:0 error:&mistake];
if (mistake) {
NSLog(#"Mistake: %#", mistake);
} else {
NSLog(#"No mistake");
}
the can identifier returns '1' so I'm assuming the error is not with the data that Facebook is providing.
The data from Facebook is returning fine, this is a sample of results:
data = (
{
"page_id" = 253370381511811;
type = "PUBLIC FIGURE";
},
{
"page_id" = 148389618201;
type = "LOCAL BUSINESS";
},
{
"page_id" = 213631462169238;
type = COMMUNITY;
}
I don't know that library, but the code that you wrote cannot possibly work.
isValidJSONObject is a method that checks whether you have an object that can be serialised to JSON, that is an NSArray or NSDictionary containing only keys and values that can be serialised to JSON.
JSONObjectWithData is a method that takes an NSData object and deserialises it to an NSArray or NSDictionary.
Since an NSData object will always fail in isValidJSONObject, and an NSDictionary or NSArray is never valid input for JSONObjectWithData, one of these calls must fail.
I am working on iPhone application and getting response from server and i parse the response string using JSON Parser it returns the dictionary. now i am not under stand how to use the data because it is came with back slash, i have print the data on console i am sending this related image please check the image give a solution to me. i am working on this problem from the last 6hrs onwards. please give me solution.!
(
"{\"category_id\":\"1\", \"category_name\":\"BEVERAGES\", \"image_id\":\"6\"}",
"{\"category_id\":\"1\", \"category_name\":\"BEVERAGES\", \"image_id\":\"7\"}",
"{\"category_id\":\"3\", \"category_name\":\"BREAKFAST\", \"image_id\":\"5\"}",
"{\"category_id\":\"3\", \"category_name\":\"BREAKFAST\", \"image_id\":\"6\"}",
"{\"category_id\":\"4\", \"category_name\":\"ALA CARTE\", \"image_id\":\"2\"}
),
(
"{\"subcategory_id\":\"1\",\"category_id\":\"3\", \"subcategory_name\":\"COMBOS\", \"image_id\":\"\"}",
"{\"subcategory_id\":\"2\",\"category_id\":\"3\", \"subcategory_name\":\"OMELETES\", \"image_id\":\"\"}",
"{\"subcategory_id\":\"3\",\"category_id\":\"3\", \"subcategory_name\":\"GRIDDLES\", \"image_id\":\"\"}"
),
NSError* error = nil;
NSArray* jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
if (jsonArray == nil) {
NSLog(#"Error getting jsonArray: %#", error);
// Handle error condition
}
NSArray* categoryArray = jsonArray[0];
for (NSString* innerJson in categoryArray) {
NSData* innerJsonData = [innerJson dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* innerDict = [[NSJSONSerialization JSONObjectWithData:innerJsonData options:0 error:&error];
if (innerDict == nil) {
NSLog(#"Error getting innerDict: %#", error);
// Handle error condition
}
NSString* category_id = innerDict[#"category_id"];
// etc
}
// Repeat for subcategoryArray = jsonArray[1]
I am trying to convert a string into a json object and am unsure why this is not working. When I nslog the output I am told that urldata is not valid for json serialization however when looking at the string it looks to me like valid json. I have also tried encoding it to an utf8 however it still won't serialize. Am I missing something here? - Note unnecessary code omitted from post.
Get request
urlData = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
error:&error];
NSDictionary *tempDict = [NSDictionary alloc];
Parsing
if ([NSJSONSerialization isValidJSONObject:urlData] ) {
NSLog(#"is valid");
tempDict = [NSJSONSerialization JSONObjectWithData:urlData kniloptions error:&error];
}
NSLog(#"is not valid");
Definition:
isValidJSONObject:
Returns a Boolean value that indicates whether a given object can be converted to JSON data.
As you are already mentioning in your question, isValidJSONObject
returns a Boolean value that indicates whether a given object can be
converted to JSON data
In your case, you don't want to create JSON data, but instead create a dictionary out of JSON data. :
tempDict = [NSJSONSerialization JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
if (!tempDict) {
NSLog(#"Error parsing JSON: %#", error);
}
I am implementing forget password service in which I would pass an email address and it would return JSON to acknowledge about the sent email. The issue is that I am unable to read the response string in json, and my exception message is shown that data parameter is nil, but if I view the url in my web browser the service looks fine as mentioned below.
my code is:
NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];
NSData* data = [NSData dataWithContentsOfURL: url];
#try {
NSError* error;
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data //1
options:0
error:&error];
NSLog(#"%#", [jsonDict objectForKey:#"response"]);
}
#catch (NSException *exception) {
NSLog(#"forgot password exception: %#: %#", [exception name], [exception reason]);
}
and the service response I get in my web browser is like this:
{"status":400,"response":"Your request to change password is already sent. Please check your email."}
Exception:
forgot password exception: NSInvalidArgumentException: data parameter is nil
in Objective-C exceptions are only used for fatal errors, not recoverable errors. Instead just check for nil data:
If you need to know what was the reason for failure, use:
NSError* error;
NSURL *url = [LokalmotionCommonTask getURLForgotPassword:emailFieldTxt.text];
NSData* data = [NSData dataWithContentsOfURL: url options:NULL error:&error];
if (data) {
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data //1
options:0
error:&error];
NSLog(#"%#", [jsonDict objectForKey:#"response"]);
}
else {
NSLog(#"forgot password error, %#", [error localizedFailureReason]);
}
There is a naming convention error: getURLForgotPassword:
A method name that begins with "get" implies that there will be a return by reference parameter. Better to just name the method: forgotPasswordURL:
These two things, exceptions and accessors prefixed with get are a basic difference from Jave.
There error says data parameter is nil. So the variable you pass for the JSON-date probably is nil.
[NSData dataWithContentsOfURL:url] probably returns nil since an error occured. Try logging that.
Also, even if it is only a small file you request, I would go for an asynchronous request in order not to block the UI.
i was facing the same problem, problem was that i have given extra space in the url string that was url string #" http:...." corrected it by removing space in the start of url string #"https:...."
Solved that by fixing service URL, my url was not encoded and had spaces inline
I have a web service that returns a raw string of JSON data (sample below)
{'d':{'success':true,'msg':null,'data':[{'productId':'4b7fcb0f818e4a4abaf5b3c78654b631','id':4283}]}}
... And when I attempt to parse this JSON using the popular JSON library for iPhone development I notice a problem in the following method
- (id)objectWithString:(NSString *)repr {
[self clearErrorTrace];
if (!repr) {
[self addErrorWithCode:EINPUT description:#"Input was 'nil'"];
return nil;
}
depth = 0;
c = [repr UTF8String];
id o;
if (![self scanValue:&o]) {
return nil;
}
// more code ...
}
When I hit the last if statement shown I show c to be a valid char (showing the json values inside as expected) but I notice that after o is defined I return nil inside that last if causing this error from the library
#import "NSString+SBJSON.h"
#import "SBJsonParser.h"
#implementation NSString (NSString_SBJSON)
- (id)JSONValue
{
SBJsonParser *jsonParser = [SBJsonParser new];
id repr = [jsonParser objectWithString:self];
if (!repr)
NSLog(#"-JSONValue failed. Error trace is: %#", [jsonParser errorTrace]);
[jsonParser release];
return repr;
}
#end
Any idea what might be wrong with taking a string of what looks like json and trying to parse it like the below?
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSArray *json = [responseString JSONValue]; //here it all fails
}
Just as a note- this works without error when I query a valid json web service from a large company. My app is aspnet mvc and the return line is simply
return this.Content(jsonStringValue, "text/json");
You should use the built in JSON result object from your action method instead of the Content() method:
return Json(data);
It will automatically serialize your object to be valid JSON.
It would be useful to provide actual error messages/traces.
At any rate, your JSON string is not valid: a string in JSON is quoted within double quotes, not single quotes. The following is valid JSON:
{"d":{"success":true,"msg":null,"data":[{"productId":"4b7fcb0f818e4a4abaf5b3c78654b631","id":4283}]}}
Edit: note that your JSON (top level) data represents an object, not an array. Hence
NSArray *json = [responseString JSONValue];
should be replaced with
NSDictionary *json = [responseString JSONValue];
because SBJSON represents JSON objects as dictionaries.