Parse json from URL in objective c - objective-c

I am trying to parse some JSON from a URL in objective C.
The output is fine, however, when I try to get the value of the notifications.id key it returns a SIGBRT error.
Code:
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&serializeError];
success = [jsonData[#"ERROR"] integerValue];
if (success == 0) {
NSLog(#"%#", jsonData[#"notifications"][#"id"]);
}else{
}
Example JSON is:
{"notifications":[{"id":"fae9a890-2791-46e2-ad9c-5a72f602a2e8","created":"2017-06-17T21:57:28+00:00","thread_id":3964,"reply_id":null,"thread":{"id":3964,"subject":"[CakePHP]
Pagination"},"users_from":{"username":"Royal"},"content":"has posted a
reply
in"},{"id":"00732627-f23e-423e-b885-add968575972","created":"2017-06-17T20:08:05+00:00","thread_id":3964,"reply_id":79478,"thread":{"id":3964,"subject":"[CakePHP]
Pagination"},"users_from":{"username":"Royal"},"content":"has quoted
you in"}]}
How can I fix this?
Thanks.

The object for key notifications is clearly an array. Please read the JSON: [] is array, {} is dictionary.
NSArray *notifications = jsonData[#"notifications"];
for (NSDictionary * notification in notifications) {
NSLog(#"%#", notification[#"id"]);
}

Related

Facebook json data error, cocoa error 3840

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.

How to insert the data into sqlite

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]

Issue with parsing JSON data

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);
}

Objective C NSJSONSerialization how to parse sub json

how to handle a json object with a sub object in the string. Here is an example
[{"_id":"1","Title":"Pineapple","Description":"Dole Pineapple","Icon":"icon.png","Actions":{"ACTION_PHOTO":"coupon.png", "ACTION_LINK":"google.com"}}]
How do you parse the second json "Actions" ?
What you have here is an array of dictionaries (with 1 entry), where one of the entries in the top level dictionary is also a dictionary. So you might have something like this to parse it:
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error: &e];
if (jsonArray) {
NSDictionary *dictActions;
for (NSDictionary *dict in jsonArray) {
dictActions = [dict objectForKey:#"Actions"];
NSLog(#"The action link is: %#", [dictActions objectForKey#"ACTION_LINK"]);
}
} else {
NSLog(#"Error parsing JSON: %#", [e localizedDescription]);
}

How to return a raw string of text/json from aspnet mvc and parse it with the iPhone JSON library

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.