add objects to JSON array - ios

I've been looking into/using web service and I managed to extract and use JSON text from a server. At the moment, Im looking into sending info back, but I've had no luck. In my JSON file I have an array which I would like to add-on to through the use of Xcode. I've tried many things to no avail.
NSError *error;
NSDictionary *jsonDict = #{ #"myArray":#"NewObject"};
NSData* postData = [NSJSONSerialization dataWithJSONObject:jsonDict options:kNilOptions error:&error];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url1 = [NSURL URLWithString:[NSString stringWithFormat:#"url going to JSON file"]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"Reply: %#", theReply);
I based this code on another post, but I clearly don't understand, because its not adding anything to the JSON array. Just to clarify, I want to make it so that the new object that is added stays in the .json file.
EDIT: Since there is a bit of confusion Im posting the JSON code
{
"mykey": "myvalue",
"myarray": [
"one",
"two"
]
}
The objective is so that in the .json file in the "myarray" it would be "one","two","NewObject". The text "NewObject" would be a string that is coming from Xcode . Sorry for not being clear.

Related

How to make an array of string (String has json data)

I Want to make a string like below
contentlist=["{\"id\":\"id1\"}"]
How can i achieve this ?
I tried with NSString method stringWithFormat:#"contentlist=[\"%#\"]
but it has \ character when you copy that string and paste it into textedit or in stickies or anywhere.
if you print this line that it will display like contentlist=["{"id":"id1"}] that i dont want.
Edited :
Here is my code..
NSString *stringUrl = <MY SERVER URL STRING>
NSString *param = [NSString stringWithFormat:#"contentlist=[%c%#%c]",34,header,34];
NSData *postData = [param dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSError *error;
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:stringUrl parameters:nil error:&error];
req.timeoutInterval= 40.0;
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:postLength forHTTPHeaderField:#"Content-Length"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setHTTPBody:postData];
And my header value is..
{\"id\":\"21ca7309\",\"indexVersion\":0,\"modified\":1501694202014,\"created\":1501691797232,\"modifiedBy\":\"42bebd87be6ddd4a\",\"name\":\"abcd\"}
How my param value look like in debug mode..
#"contentlist=[\"{\"id\":\"21ca7309\",\"indexVersion\":0,\"modified\":1501694202014,\"created\":1501691797232,\"modifiedBy\":\"42bebd87be6ddd4a\",\"name\":\"abcd\"}\"]
And how I need to pass is like :
contentlist:["{\"id\":\"21ca7309\",\"indexVersion\":0,\"modified\":1501694202014,\"created\":1501691797232,\"modifiedBy\":\"42bebd87be6ddd4a\",\"name\":\"abcd\"}"]
You don't required to use stringWithFormat
as you mentioned you have NSData of JSON if you don't have that then convert it using
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:yourJSONO options:NSJSONWritingPrettyPrinted error:&error];
Don't forgot to check error before use :)
you can easily get string from that with below code
NSString *str = [[NSstring alloc] initWithData:data encoding:NSUTF8StringEncoding]

Unsupported URL when sending Json value as argument in GET method

Code:
arrValues = [[NSMutableArray alloc]initWithObjects:#"Chennai", nil];
arrKeys = [[NSMutableArray alloc]initWithObjects:#"loc", nil];
dicValue = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];
NSString *strMethodName = #"agentuserlist";
strUrlName = [NSString stringWithFormat:#"%#%#?filters=%#",appDelegate.strURL, strMethodName, dicValue];
//strUrlName = [strUrlName stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:strUrlName] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:250.0];
[request setHTTPMethod:#"GET"];
[request setHTTPShouldHandleCookies:YES];
[request setValue:#"zyt45HuJ70oPpWl7" forHTTPHeaderField:#"Authorization"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
NSError *error;
NSURLResponse *response;
NSData *received = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&error];
NSLog(#"error:%#", error);
NSString *strResponse = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
NSLog(#"response :%#", strResponse);
I try to send json argument through get method.It gives error as "unsupported url(-1002)".
The URL is working fine when I checked with Postman. I am unable to find out the problem.
Where I went wrong?
I think the problem lies in how you encode your NSDictionary in the NSURL.
You probably want your URL to look like this: http://my domain.com/agentuserlist?loc=Chennai. But the raw encoding of the NSDictionary inside the NSURL doesn't produce this result.
You can follow the accepted answer
from this question to get an idea of how to transform an NSDictionary into a regular list of URL parameters (with proper encoding of dictionary values: don't forget the stringByAddingPercentEscapeUsingEncoding part): Creating URL query parameters from NSDictionary objects in ObjectiveC

How to reach members of json with iOS

I want to reach from ios to a .net .asmx web service, and I reach with the following code:
NSString *urlString = #"http://www.****.com/Mobile.asmx/HelloWorld";
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: #"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned)
{
//...handle the error
}
else
{
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#", retVal);
//...do something with the returned value
}
It returns clean json {"hellom":"Hello World","hellom2":"HelloWorld2"} but I can't reach members and value one by one
How can I do that?
You can convert JSON data into an object by using the following code...
NSData *jsonData = ... the data you got from the server
NSDictionary *object = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
object will then be a NSDictionary like this...
#{
hellom : #"Hello World",
hellom2: #"HelloWorld2"
}
You can then get to the keys and values like any other dictionary.

IOS to REST-ful MVC Api Service - [Get] works, but parameters don't reach server with [Post]

I think the title explains it. I can reach the Get functions on my api controllers just fine. I can reach the Post method, but my parameter (macAddress) is null. I've tried many variations of this code in xcode:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#",baseURL,controller]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
NSString *postString = #"macAddress=testestest";
NSData *myRequestData = [ NSData dataWithBytes: [ postString UTF8String ] length: [ postString length ] ];
[request setHTTPBody:myRequestData];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
and the controller:
public String Post([FromBody]string macAddress)
{
//......
}
(I'm aware that I'm using synchronous requests and nil response/errors, just trying to figure out this aspect)
Thanks for the help.
It looks like you have your *postString without the [NSString stringWithFormat method]. I use the following code with my own restful API.
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"rsdevicetoken"];
NSString *postString = [NSString stringWithFormat:#"token=%#&active=%#&draw=%#&result=%#&message=%#",deviceToken,allNotify, draw, results, message];
NSData *postData = [postString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://www.someurl.com/updateSubscriptions"]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#", data);
Hopefully this will help you.
It's a wild guess but if your macAddress post param has the following format: 01:23:45:67:89:ab you need to url encode the ':' to '%3A'.

How to send recursive json request with nsmutableurlrequest in ios?

in iOS to create this
"{
"email":string,
"password":string
}"
json request body, i am passing the nsdata that i create from the string
email=myname#domain.com&password=mypassword
to the setHTTPBody method of the NSMutableURLRequest.This works fine im ok with this.
But what if i want to create this
"{
"post":
{
"title":string,
"room_id":int,
"content":string,
}
}"
json request body? i tried to make some string combinations to solve this recursion but didnt work out really. I also checked the methods of NSMutableURLRequest but i couldnt find something related to solve this.
edit:
This creates the post as it should be its fine, but i need an equivalent to the string email=myname#domain.com&password=mypassword for the recursive case. When i send the data as it should be it does not work. When i send as the string that i provided it works.
NSString *usertoken = [appDelegate token];
NSString *posttopic = #"111testtopic";
NSString *postbody = #"111testbody";
NSDictionary *dict = #{#"post":#{#"title":posttopic,#"room_id":#"246",#"content":postbody}};
NSData *body = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *postLength = [NSString stringWithFormat:#"%d", [body length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
//send the post
NSString *urlstring = [NSString stringWithFormat:#"http://mydomain.com/posts.json?auth_token=%#", usertoken];
[request setURL:[NSURL URLWithString:urlstring]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:body];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
Try this
NSDictionary *dict = #{#"post":#{#"title":string,#"room_id":int,#"content":string}};
NSData *body = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
the idea is to use some nested dictionaries to describe your json and serialize them to get your jsonData to pass to the request.

Resources