iOS send JSON array in POST - ios

I want to create a JSON array of the following structure:
"Create Account":{
"RegistryNumber":"",
"People":[{
"PeopleId":"",
"email":"",
"pass":"",
}]
}
I am using the folllowing code to do it:
NSDictionary *content0 = [NSDictionary dictionaryWithObjectsAndKeys:
#"PeopleId", #"0",
#"email", #"email",
#"pass", #"pass",nil];
NSArray *peopledetails = [NSArray arrayWithObjects:content0,nil];
NSMutableDictionary *peopleDict = [[NSMutableDictionary alloc] init];
[peopleDict setObject:#"content0" forKey:#"People"];
NSMutableDictionary *details = [[NSMutableDictionary alloc] init];
[details setObject:#"RegistryNumber" forKey:#"RegistryNumber"];
[details setObject:#"peopleDict" forKey:#"People"];
NSMutableDictionary *MainDict = [[NSMutableDictionary alloc] init];
[MainDict setObject:#"details" forKey:#"Create Account"];
But this gives me an error from the server. I have other API which works fine when array is not in picture.

- (void)simpleJsonParsing
{
// URL request with server
NSHTTPURLResponse *response = nil;
NSString *jsonUrlString = [NSString stringWithFormat:#"URL"];
NSURL *url = [NSURL URLWithString:[jsonUrlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//-- Get request and response though URL
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//-- JSON Parsing
NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Result = %#",result);
for (NSMutableDictionary *dic in result)
{
NSString *string = dic[#"Create Account"];
if (string)
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
dic[#"Create Account"] = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
}
else
{
NSLog(#"Error in response");
}
}
}

change
[peopleDict setObject:#"content0" forKey:#"People"];
to
[peopleDict setObject:peopledetails forKey:#"People"];
Remove all #"" for objects.
#"details" is a string and details is an object
Or here is the simple way
NSDictionary *dict=#{
#"Create Account": #{
#"RegistryNumber": #"",
#"People": #[
#{
#"PeopleId": #"",
#"Email": #"",
#"pass":#""
}
]
}
};

I think you have wrong structure
NSDictionary *content0 = [NSDictionary dictionaryWithObjectsAndKeys:
#"PeopleId", #"0",
#"email", #"email",
#"pass", #"pass",nil];
postDict = #{#"Create Account":#{#"RegistryNumber":"","People":content0}}
now convert this into jason and send to your server

Related

Creating NSDictionary

how i can create Dictionary that when i create jsondata with it, json looks like :
"historyStep":[
{
"counter": "50",
"timestamp": "1461674383632"
}
]
I did this :
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:jsonDictOth,#"historyStep", nil];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:NSJSONWritingPrettyPrinted
error:&error];
but it looks :
historyStep = {
counter = 810;
timestamp = "1464957395241.447998";
};
You are missing a level: NSDictionary (top level) with NSArray of NSDictionary in the top level key historyStep:
NSMutableDictionary *topLevel = [[NSMutableDictionary alloc] init];
NSArray *historySteps = [[NSMutableArray alloc] init];
//Here you may have a for loop in case there are more steps
NSDictionary *aStep = #{#"counter":#"50", #"timestamp":#"1461674383632"};
[historySteps addObject:aStep]
[topLevel setObject:historySteps forKey#"historyStep"];
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:topLevel
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *innerDictionary = [[NSDictionary alloc]initWithObjectsAndKeys:#"50", #"counter",#"1461674383632", #"timestamp", nil];
NSArray *array = [[NSArray alloc]initWithObjects:innerDictionary, nil];
NSDictionary *outerDict = [[NSDictionary alloc]initWithObjectsAndKeys:array, #"historyStep", nil];
Use this code it will work perfectly.
Your code should be like,
NSMutableDictionary*jsonDictOth = [[NSMutableDictionary alloc]init];
[jsonDictOth setObject:#(810) forKey:#"counter"];
[jsonDictOth setObject:#"1464957395241.447998" forKey:#"timestamp"];
NSMutableArray *arr = [[NSMutableArray alloc]init];
[arr addObject:jsonDictOth];
NSMutableDictionary *jsonDictMain = [[NSMutableDictionary alloc]initWithObjectsAndKeys:arr,#"historyStep", nil];
NSLog(#"jsonMain is %#",jsonDictMain);
NSError*error;
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictMain
options:0
error:&error];
It's output is,
jsonMain is {
historyStep = (
{
counter = 810;
timestamp = "1464957395241.447998";
}
);
}
You just missed one array between

How to parse such a json array?

Im having hard time while trying to parse the following json array. How to parse it. The other answers in web doesn't seem to solve my problem.
{
"status": 1,
"value": {
"details": [
{
"shipment_ref_no": "32",
"point_of_contact": {
"empid": ""
},
"products": {
"0": " Pizza"
},"status": "2"
},
{
"shipment_ref_no": "VAPL/EXP/46/14-15",
"point_of_contact": {
"empid": "60162000009888"
},
"products": {
"0": "MAIZE/CORN STARCH"
},
"status": "5"
}
]
}
}
I have to access the values of each of those keys.
Following is my code
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
This is how you can parse your whole dictionary:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *details = [[dataDictionary objectForKey:#"value"] objectForKey:#"details"];
for (NSDictionary *dic in details) {
NSString *shipmentRefNo = dic[#"shipment_ref_no"];
NSDictionary *pointOfContact = dic[#"point_of_contact"];
NSString *empId = pointOfContact[#"empid"];
NSDictionary *products = dic[#"products"];
NSString *zero = products[#"0"];
NSString *status = dic[#"status"];
}
NSString *pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
//argsArray holds objects in form of NSDictionary.
for(NSDictionary *response in argsArray) {
//String object
NSLog(#"%#", [response valueForKey:#"shipment_ref_no"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"point_of_contact"] valueForKey:#"empid"]);
//String object
NSLog(#"%#", [response valueForKey:#"status"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"products"] valueForKey:#"0"]);
}
I believe you should surely ask your server developer to update the response format.
Also, you can always use Model classes to parse your data. Please check this, How to convert NSDictionary to custom object.
And yes, I'm using this site to check my json response.
EDIT: Following answer is in javascript!
You can parse your json data with:
var array = JSON.parse(data);
and then you can get everything like this:
var refno = array["value"]["details"][0]["shipment_ref_no"];
you can parse like ...
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *dictValue = [[NSDictionary alloc] initWithDictionary:[jsonDic objectForKey:#"value"]];
NSArray *arrDetails = [[NSArray alloc] initWithArray:[dictValue objectForKey:#"details"]];
for (int i=0; i<arrDetails.count; i++)
{
NSDictionary *dictDetails=[arrDetails objectAtIndex:i];
NSDictionary *dictContact = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"point_of_contact"]];
NSDictionary *dictProduct = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"products"]];
}
NSDictionary *response = //Your json
NSArray *details = response[#"value"][#"details"]
etc. Pretty easy
Update your code as follows. You are trying to read the details array from the top level whereas in your data its inside the value key. So you should read the value dict and within that read the details array.
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *valueDict = [jsonDic objectForKey:#"value"];
NSArray *argsArray = [[NSArray alloc] initWithArray:[valueDict objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
I think your problem is that you have:
NSLog(#"keys = %#", jsonDic[#"values"]);
But it should be:
NSLog(#"keys = %#", jsonDic[#"value"]);
Below is code for parsing JSON array. i have used to parse JSON array from file but you can also do this using response link also.I have provided code for both and are below.
// using file
NSString *str = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
NSData *data = [[NSData alloc]initWithContentsOfFile:str];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
// using url
NSURL *url = [NSURL URLWithString:#"www.xyz.com"]; // your url
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);

Double Object Nesting JSON Response Body [Objective C]

In Objective C how should I write a Double Nested Response Body along the form:
{'ms_request':
{'user':
{'api_key':'',
'username':'',
'password':''
}
}
}
I know how to do it for one object, but double nesting the objects has me stumped.
Here is what I have so far:
NSArray *loginDetails = [self authenticationHelper];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
[loginDetails objectAtIndex:0], #"password",
[loginDetails objectAtIndex:1], #"username",
[loginDetails objectAtIndex:2], #"api_key",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
NSMutableURLRequest *request =
[[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:autheticationURL]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:postdata];
You could also use NSDictionary literals. Something like this (just make sure that you check all the values to avoid insertion of nil objects):
NSDictionary *reqDict =
#{#"ms_request":
#{#"user":
#{#"api_key":loginDetails[2],
#"username":loginDetails[1],
#"password":loginDetails[0]
}
}
};
You have to add dictionary in another dictionary.
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
[loginDetails objectAtIndex:0], #"password",
[loginDetails objectAtIndex:1], #"username",
[loginDetails objectAtIndex:2], #"api_key",
nil];
NSDictionary *userDict = [[NSDictionary alloc] initWithObjectsAndKeys:
tmp, #"user"];
NSDictionary *requestDict = [[NSDictionary alloc] initWithObjectsAndKeys:
userDict, #"ms_request"];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestDict options:0 error:&error];
PS: In JSON, { } represents dictionary and [ ] represents array.

How to convert NSArray of NSStrings into Json String iOS

I have an Array of Roll Numbers
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
I need to send this array in a Web Service request
whose format is like this (in JSON format)
JSON data
{
"existingRoll":["22","34","45","56"], // Array of roll numbers
"deletedRoll":["20","34","44","56"] // Array of roll numbers
}
but I am facing problem in converting Array of Roll numbers (rollArray) into json String
in the desired format.
I am trying this
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:[rollArray componentsJoinedByString:#","] forKey:#"existingRoll"];
NSString *str = [Self convertToJSONString:postDict]; // converts to json string
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:str options:0 error:nil];
[request setHTTPBody:jsonData];
I am using iOS 7
There is no need to use the following code snippets:
[rollArray componentsJoinedByString:#","]
NSString *str = [Self convertToJSONString:postDict];
You can create JSON by using the following code:
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];
[postDict setValue:rollArray forKey:#"existingRoll"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSLog(#"%#",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
Try this :
NSDictionary *object = #{
#"existingRoll":#[#"22",#"34",#"45",#"56"],
#"deletedRoll":#[#"20",#"34",#"44",#"56"]
};
if ([NSJSONSerialization isValidJSONObject:object]) {
NSData* data = [ NSJSONSerialization dataWithJSONObject:object options:NSJSONWritingPrettyPrinted error:nil ];
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(str);
}
NSMutableDictionary *postDict = [[NSMutableDictionary alloc] init];
[postDict setValue:#"Login" forKey:#"methodName"];
[postDict setValue:#"admin" forKey:#"username"];
[postDict setValue:#"12345" forKey:#"password"];
[postDict setValue:#"mobile" forKey:#"clientType"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict options:0 error:nil];
// Checking the format
NSString *urlString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
// Convert your data and set your request's HTTPBody property
NSString *stringData = [[NSString alloc] initWithFormat:#"jsonRequest=%#", urlString];
//#"jsonRequest={\"methodName\":\"Login\",\"username\":\"admin\",\"password\":\"12345\",\"clientType\":\"web\"}";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
You can use following method to get Json string from any type of NSArray :
NSArray *rollArray = [NSArray arrayWithObjects:#"1", #"22", #"24", #"11", nil];
NSData *data = [NSJSONSerialization dataWithJSONObject:rollArray options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"Json string is: %#", jsonString);

Converting NSData into NSDictionary

I get the data from an XML file and I am storing it in NSData object. I want to convert that NSData into an NSDictionary and store that data in a plist.
My code is as follows:
NSURL *url = [NSURL URLWithString:#"http://www.fubar.com/sample.xml"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"%#", data);
To convert the data, I am using:
- (NSDictionary *)downloadPlist:(NSString *)url {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
NSURLResponse *resp = nil;
NSError *err = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err];
if (!err) {
NSString *errorDescription = nil;
NSPropertyListFormat format;
NSDictionary *samplePlist = [NSPropertyListSerialization propertyListFromData:responseData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&errorDescription];
if (!errorDescription)
return samplePlist;
[errorDescription release];
}
return nil;
}
Can anyone please tell me how to do that?
or this:
NSString* dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *jsonParser = [SBJSON new];
NSDictionary* result = (NSDictionary*)[jsonParser objectWithString:dataStr error:nil];
[jsonParser release];
[dataStr release];
Try this code:
NSString *newStr1 = [[NSString alloc] initWithData:theData1 encoding:NSUTF8StringEncoding];
NSString *newStr2 = [[NSString alloc] initWithData:theData2 encoding:NSUTF8StringEncoding];
NSString *newStr3 = [[NSString alloc] initWithData:theData3 encoding:NSUTF8StringEncoding];
NSArray *keys = [NSArray arrayWithObjects:#"key1", #"key2", #"key3", nil];
NSArray *objects = [NSArray arrayWithObjects:newStr1 , newStr2 , newStr3 , nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
for (id key in dictionary) {
NSLog(#"key: %#, value: %#", key, [dictionary objectForKey:key]);
}
NSString *path = [[NSBundle mainBundle] pathForResource:#"Login" ofType:#"plist"];
[dictionary writeToFile:path atomically:YES];
//here Login is the plist name.
Happy coding

Resources