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];
Related
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);
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];
How to upload video on facebook using facebook sdk 4.6 on iOS8.This is the code i used:
FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/photos" parameters:params tokenString:token.tokenString version:#"nil" HTTPMethod:#"POST" ];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error)
NSLog(#"%#", error);
else
NSLog(#"Success");
}];
[connection start];
any help appreciated.
Try this code. it works for me.
NSDictionary *dictPrivacy = [NSDictionary
dictionaryWithObjectsAndKeys:#"FRIENDS_OF_FRIENDS",#"value",
nil];
SBJSON *jsonWriter = [SBJSON new];
NSString *strPrivacy = [jsonWriter stringWithObject:dictPrivacy];
NSString *Url = [[NSBundle mainBundle] pathForResource:#"Video" ofType:#"MOV"];
NSData *videoData = [NSData dataWithContentsOfFile: videoUrl];
//NSData *videoData = [NSData dataWithContentsOfFile:rtfUrl];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
csString, #"title",
strPrivacy,#"privacy",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (error)
{
NSLog(#"fail to upload over Facebook");
}
else
{
NSLog(#"Successfully uploaded over Facebook");
}
}];
In Graph APi 2.3+
FBSDKShareVideo *video = [[FBSDKShareVideo alloc] init];
video.videoURL = videoURL;
FBSDKShareVideoContent *content = [[FBSDKShareVideoContent alloc] init];
content.video = video;
[FBSDKShareAPI shareWithContent:content delegate:self];
NOTE: Video URL should be Assest URL.
If one don't want to use FBSDKShareVideo.
- (void)shareVideoOnFacebook:(NSString*)videoURL{
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]){
NSData *videoData = [NSData dataWithContentsOfFile:videoURL];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#" ", #"title",
#" ", #"description",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error){
if (!error){
NSLog(#"sharing result = %#",result);
}
else{
NSLog(#"error=%#",error.localizedDescription);
}
}];
} else{
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
loginManager.loginBehavior = FBSDKLoginBehaviorNative;
[loginManager logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error || result.isCancelled) {
NSLog(#"fb error= %#",error.localizedDescription);
}
else{
NSData *videoData = [NSData dataWithContentsOfFile:videoURL];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#" ", #"title",
#" ", #"description",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error){
if (!error){
NSLog(#"sharing result = %#",result);
}else{
NSLog(#"error=%#",error.localizedDescription);
}
}];
}
}];
}
}
I am new to objective-c and need to submit collection of json objects.
I wrote the following:
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
id, #"id",
toClientGroupType, #"toClientGroupType",
dueDate, #"dueDate",
actionDate, #"actionDate",
campaignType, #"campaignType",
campaignCategory, #"campaignCategory",
businessId, #"businessId",
promotion, #"promotion",
product, #"product",
contentF, #"content",
subject, #"subject",
nil];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
[request setURL:[NSURL URLWithString:#"https://services-dev.a.com/api/channels"]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:jsonData2];
I have 2 problems:
A. The output of jsonData as String is
{
"toClientGroupType" : "VIP",
"id" : "1",
"dueDate" : "2012-09-03 10:25:42 +0000",
"actionDate" : "2012-09-03 10:25:42 +0000",
"campaignType" : "ONE_TIME",
"businessId" : "150",
"campaignCategory" : "SALE"
}
As you see - I am missing 3 fiels which I declared: content, product and subject
B. I actually need to submit an array of objects so the request will be like this:
[{
"toClientGroupType" : "VIP",
"id" : "1",
"dueDate" : "2012-09-03 10:25:42 +0000",
"actionDate" : "2012-09-03 10:25:42 +0000",
"campaignType" : "ONE_TIME",
"businessId" : "150",
"campaignCategory" : "SALE"
}]
How can I do it and what is wrong?
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
id, #"id",
toClientGroupType, #"toClientGroupType",
dueDate, #"dueDate",
actionDate, #"actionDate",
campaignType, #"campaignType",
campaignCategory, #"campaignCategory",
businessId, #"businessId",
promotion, #"promotion",
product, #"product",
contentF, #"content",
subject, #"subject",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:jsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
Checkout this one
NSError *error;
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"1", #"id",
#"test", #"toClientGroupType",
#"test", #"dueDate",
#"test", #"actionDate",
#"test", #"campaignType",
#"test", #"campaignCategory",
#"test", #"businessId",
#"test", #"promotion",
#"test", #"product",
#"test", #"content",
#"test", #"subject",
nil];
NSMutableArray * arr = [[NSMutableArray alloc] init];
[arr addObject:jsonDictionary];
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
Output :-
[
{
"subject" : "test",
"toClientGroupType" : "test",
"id" : "1",
"dueDate" : "test",
"actionDate" : "test",
"campaignType" : "test",
"businessId" : "test",
"product" : "test",
"content" : "test",
"campaignCategory" : "test",
"promotion" : "test"
}
]
check out the data in to promotion, product, content and subject.it should not be nil or null
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *error;
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingAllowFragments error:&error];
NSArray *categoryArray= [dic valueForKey:#"SELECTED OBJECT KEY"];
NSLog(#"category%#",categoryArray);
}
category: Display Category array content
To problem A:
I think your fields are missing because they contain nil values. Keys that contain nil values are not considered when you use NSJSONSerialization
To problem B:
prashant has posted a good solution
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.