Method always re-writing json file - objective-c

NSURL *url = [NSURL URLWithString:#"file://localhost/Users/admin/Desktop/JSON/vivijson.json"];
NSDictionary *regDict = [[NSDictionary alloc] initWithObjectsAndKeys:self.loginString, #"login",
self.nameString, #"name",
self.lastNameString, #"lastName",
self.emailString, #"email",
self.numberString, #"number", nil];
NSError *error;
NSMutableArray *regMutArray = [[NSMutableArray alloc] init];
[regMutArray addObject:regDict];
NSData *jsonConvRegArrayData = [NSJSONSerialization dataWithJSONObject:regMutArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonRegString = [[NSString alloc] initWithData:jsonConvRegArrayData encoding:NSUTF8StringEncoding];
[jsonConvRegArrayData writeToURL:url atomically:YES];
This method are re-writing JSON, and start it again, but i need to add some to my JSON.

You should first read the exiting JSON into a mutable array using JSONObjectWithData using NSJSONReadingMutableContainers as the reading options. Then add the new array element to the mutable array returned by JSONObjectWithData and then convert it back to an JSON using dataWithJSONObject
Here's the code.
NSURL *url = [NSURL URLWithString:#"file://localhost/Users/Shared/vivijson.json"];
NSDictionary *regDict = [[NSDictionary alloc] initWithObjectsAndKeys:#"self.loginString, #"login",
self.nameString, #"name",
self.lastNameString, #"lastName",
self.emailString, #"email",
self.numberString, #"number", nil];
NSError *error;
NSMutableArray *regMutArray = [[NSMutableArray alloc] init];
[regMutArray addObject:regDict];
NSData *data = [NSData dataWithContentsOfURL:url];
NSMutableArray *array = nil;
if (data)
array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if (array == nil)
{
array = [[NSMutableArray alloc] init];
}
[array addObjectsFromArray:regMutArray];
NSData *jsonConvRegArrayData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonRegString = [[NSString alloc] initWithData:jsonConvRegArrayData encoding:NSUTF8StringEncoding];
[jsonRegString writeToURL:url atomically:true encoding:NSUTF8StringEncoding error:nil];

Related

Parsing Json to object giving "null" Value

Unable to parse this json data to object. Same code i tried with other URL, working correct. Please Suggest where i am doing wrong?
-(void)callAPI{
NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:#"https:s.json"]];
NSError *error=nil;
id response=[NSJSONSerialization JSONObjectWithData:data options:
NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:&error];
if (error) {
NSLog(#"%#",[error localizedDescription]);
} else {
NSLog(#"%#",response);}}
Output The data couldn’t be read because it isn’t in the correct format.
I got the very perfect solution for your question which works fine now.Please check the below answer
- (void)callAPI
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"GET"];
[request setURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:
^(NSData * data,
NSURLResponse * response,
NSError * error) {
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"jsonString is: %#", jsonString);
NSData *dataCon = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonVal = [NSJSONSerialization JSONObjectWithData:dataCon options:0 error:nil];
if([jsonVal isKindOfClass:[NSDictionary class]]) {
NSLog(#"The response starts with NSDictionary");
NSArray *arrJsonVal = [jsonVal objectForKey:#"rows"];
NSMutableArray *arrTitle = [[NSMutableArray alloc]init];
NSMutableArray *arrDesc = [[NSMutableArray alloc]init];
NSMutableArray *arrImage = [[NSMutableArray alloc]init];
for(NSDictionary *dict in arrJsonVal) {
NSString *strTitle = [dict objectForKey:#"title"];
NSString *strDesc = [dict objectForKey:#"description"];
NSString *strImage = [dict objectForKey:#"imageHref"];
[arrTitle addObject:strTitle];
[arrDesc addObject:strDesc];
[arrImage addObject:strImage];
}
NSLog(#"arrTitle is - %#",arrTitle);
NSLog(#"arrDesc is - %#",arrDesc);
NSLog(#"arrImage is - %#",arrImage);
}else {
NSLog(#"The response starts with NSArray");
}
}] resume];
}
The Printed results are
After that
Then Array results are
Finally the results are

How do I retrieve JSON data not on it's top level in Objective-C?

I have JSON data that looks as such:
{
"dataset": {
"id": ,
"dataset_code": "",
"database_code": "",
"name": "",
"description": "",
"refreshed_at": "",
}
}
When I go to NSLog the JSON data using the "dataset" identifier it prints fine. However I want to access the next level of JSON data which is what I'm looking to use. However, when I try to NSLog the next level I get an error in xcode. My code looks as such:
NSString *query = #"jsonwebsite.com";
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:query]];
_Array = [[NSMutableArray alloc] init];
_Array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
So if I use this it's logs fine.
NSString *testString = [_Array valueForKey:#"dataset"];
NSLog(#"%#",testString);
But as mentioned, I'm looking for the next set of data and when I try this, it gives an error.
NSString *testString = [_Array valueForKey:#"name"];
NSLog(#"%#",testString);
It returns (null). How would I be able to access the name field in this JSON data?
There is a lot wrong with your code.
_Array = [[NSMutableArray alloc] init];
_Array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
There is no point to creating an empty array in the first line, only to replace it with a different object in the second line.
Your data contains a dictionary of dictionaries, not an array. You should create a variable dictionary:
NSMutableDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
You should not use valueForKey to fetch values from your dictionary. That is a KVO method. Use objectForKey instead, or better yet, use modern dictionary syntax:
NSMutableDictionary *dataSet = dictionary[#"dataset"];
NSString *name = dataSet[#"name"];
if (name == nil) {
NSLog(#"name is nil");
}
else if (name.length == 0) {
NSLog(#"name is empty");
}
else {
NSLog(#"Name is %#", name);
}
your json is a NSDictionary not a NSMutableArray,you used a NSMutableArray to recieve a NSDictionary was wrong.
test this:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *subDict = dict[#"dataset"];
NSLog(#"%#", subDict);
NSLog(#"%#", subDict[#"name"]);
Change this code:
NSString *query = #"jsonwebsite.com";
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:query]];
_Array = [[NSMutableArray alloc] init];
_Array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSString *testString = [_Array valueForKey:#"name"];
NSLog(#"%#",testString);
into this:
NSString *query = #"jsonwebsite.com";
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:query]];
_Array = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
NSDictionary *dataSet = [_Array objectForKey:#"dataset"];
NSString *testString = [dataSet objectForKey:#"name"];
NSLog(#"%#",testString);

Create nested JSON in Objective-C

I'm trying to create JSON that looks like this:
{
"id": "feed/http://feeds.feedburner.com/design-milk",
"title": "Design Milk",
"categories": [
{
"id": "user/category/test",
"label": "test"
}
]
}
I'm doing it with this method:
NSMutableDictionary *req = [NSMutableDictionary #"feed/http://feeds.feedburner.com/design-milk" forKey:#"id"];
[req #"Design Milk" forKey:#"title"];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"user/category/test", #"id", #"test", #"label",
nil];
[req setObject:tmp forKey:#"categories"];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:req options:0 error:&error];
However, this isn't working. What am I doing wrong here?
The first line of your code isn't going to compile, so you need to fix that.
The value of "categories" in your example output is an array with one element, which happens to be a dictionary. So you need
NSDictionary* oneCategory = [NSDictionary dictionaryWithObjectsAndKeys:...];
NSArray* categories = [NSArray arrayWithObject:oneCategory];
[req setObject:categories forKey:#"categories"];
And you should really use more modern syntax, like
req [#"categories"] = #[oneCategory];
You were missing an array:
NSMutableDictionary *req =[NSMutableDictionary dictionaryWithObjectsAndKeys:#"feed/http://feeds.feedburner.com/design-milk", #"id", nil];
req[#"title"] = #"Design Milk";
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"user/category/test", #"id",
#"test", #"label",
nil];
NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:tmp];
[req setObject:arr forKey:#"categories"];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:req options:0 error:&error];

creating JSON String

I have task that involves creating the right design for the JSON string before I can get a response from the webservice. The JSON string has to look like this:
{"nid":"","vocab":"", "inturl":"testoverview", "mail":"", "md5pw":""}
and my JSON string looks like this:
"nid:",
"vocab:",
"inturl:testoverview",
"mail:",
"md5pw:"
as you can see it's not built the same way, I'm not using braces, or separating the strings the right way. And I don't know how to do this.
my code for this is here:
NSString *nid = #"nid:";
NSString *vocab = #"vocab:";
NSString *inturl = #"inturl:testoverview";
NSString *mail = #"mail:";
NSString *md5pw = #"md5pw:";
NSArray *jsonArray = [NSArray arrayWithObjects:nid, vocab, inturl, mail, md5pw, nil];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
FSProductTestHandler *handler = [[FSProductTestHandler alloc] init];
if (!jsonData) {
NSLog(#"Got an error; %#", error);
} else if(jsonData) {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSString *url = #"http://www.taenk.dk/services/mobile";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0];
[request setValue:jsonString forHTTPHeaderField:#"X-FBR-App"];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
Can anyone help me with this issue?
You are feeding an array to the serialisation which means you'll get a JSON array as output i.e soemthing like:
[ "foo", "bar", "baz"]
(note the brackets [ ...] instead of braces { ... })
You need to build an NSDictionary and for your particular example, the quickest way is like this:
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"", #"nid",
#"", #"vocab",
#"testoverview", #"inturl",
#"", #"md5pw",
#"", #"mail",
nil];
Feed that into NSJSONSerialization and you'll get what you want.

How to Parse JSON Data and display in it in an iPhone Applicaiton

I want to parse the following given all the data in and array then use in iPhone application to display.
http://www.krsconnect.no/community/api.html?method=fullEvents&appid=620
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.krsconnect.no/community/api.html?method=fullEvents&appid=620"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSArray *results = [parser objectWithString:json_string error:nil];
NSDictionary *dictOne = [results objectAtIndex:0];
NSArray *activitiesArray = [dictOne objectForKey:#"activities"];
NSDictionary *dictTwo = [activitiesArray objectAtIndex:0];
NSDictionary *eventDict = [dictTwo objectForKey:#"event"];
NSDictionary *dictThree = [activitiesArray objectAtIndex:0];
NSDictionary *eventDict3 = [dictThree objectForKey:#"images"];
NSLog(#"%# - %#", [eventDict3 objectForKey:#"large"]);
NSLog(#"%# - %#", [eventDict objectForKey:#"category"]);
NSLog(#"%# - %#", [eventDict objectForKey:#"content"]);
It's working fine but if I print HoursFrom from dates object it's not printing
That'll be because in your data feed, it's hoursFrom, not HoursFrom. The case is significant.