i want to make a structure like following using NSDictionary
{
"request":
{
"email":"manger#abc.com",
"password":"manager"
}
}
I'm using the following code in objective C
NSDictionary *paramsDic = [[NSDictionary alloc] initWithObjectsAndKeys:
#"manger#hall.com",#"email",
#"manager",#"password",
nil];
NSDictionary *req = [[NSDictionary alloc] initWithObjectsAndKeys:
paramsDic,#"request",
nil];
but it returns the following response
{
request =
{
email = "manger#abc.com";
password = manager;
};
}
it shows semicolons instead of commas , one extra semicolon and keys are not in inverted commas
Convert req to JSON object
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:req options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"%#", jsonData);
Related
There is an api that I need to post the geoPoint, then get data, which works fine on Postman. Like shown in the image,
this api works fine on Postman
In my code, I use the following way to call api
NSArray *geoPoint = #[#114.33f, #22.44f];
NSDictionary *geoPointDic = # {#"geoPoint" : geoPoint};
NSDictionary *inData = #{
#"action" : #"getNearbyEventList",
#"data" : geoPointDic};
NSDictionary *parameters = #{#"data" : inData};
NSLog(#"geoPoint is %#", geoPoint);
NSLog(#"upcoming events parameters %#", parameters);
[_manager POST:GetURL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, NSDictionary * responseObject) {
NSLog(#"responseObject is %#", responseObject);
NSLog(#"responseObject - data is %#", responseObject[#"data"]);
NSArray *eventsArray = responseObject[#"data"];
But the output is
when NSLog parameters:
events parameters {
data = {
action = getNearbyEventList;
data = {
geoPoint = (
"114.33",
"22.44"
);
};
};
}
the api response looks like
I guess my parameters might be in wrong format, so I tried the following way, but no one works
//NSArray *geoPoint = [[NSArray alloc] init];
//NSArray *geoPoint = [[NSArray alloc] initWithObjects:#"114", #"22", nil];
//NSMutableArray *geoPoint = [[NSMutableArray alloc] init];
//[geoPoint addObject:#114];
//[geoPoint addObject:#22];
//NSArray *geoPoint = [[NSArray alloc] initWithObjects:#"114", #"22", nil];
//NSString *geoPoint = #"[114.33,22.44]";
So, could anyone tell me how to get the data like shown in the Postman, please?
Thanks a lot!
You can try:
NSData *dataBody = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];
NSString *json = [[NSString alloc] initWithData:dataBody encoding:NSUTF8StringEncoding];
NSLog(#"%#",json);
Object json same is data you send to server.
I received NSData object data from REST API. That contains JSON data which I want to parse.
{
JsonResult = "[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
}
This statement gave me the result as a String like below which I am not able to parse as JSON.
myData = [data valueForKey:#"JsonResult"];
"[{
\"IsAuth\":\"true\",
\"User\":\"
[
{
\\\"userid\\\":\\\"josephH\\\",
\\\"firstname\\\":\\\"joseph\\\",
\\\"lastname\\\":\\\"Henry\\\",
}
]\"}]"
When I try to pass this mydata to JSONSerialization the code crashes.
How do I cast the above string to NSDictionary so that I can parse them and use the values of IsAuth and User.?
Code:
[LDService authenticateUser:Uname.text passwordString:Password.text completeBlock:^(NSData * data){
NSError *error;
NSData *jsonData;
NSString *jsonString = nil;
NSMutableDictionary *jsonDict;
if([NSJSONSerialization isValidJSONObject:data])
{
jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
NSLog(#"Formatted string %#",formattedString);
[jsonDict setObject:formattedString forKey:#"JsonResult"];
NSLog(#"Parsed json %#",jsonDict);
}];
Pass your data as data
NSError *error;
NSString *jsonString = nil;
if([NSJSONSerialization isValidJSONObject:data])
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:data
options:kNilOptions
error:&error];
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
then replace occurance of #"\\\" with #"'"
NSString *formattedString = [jsonString stringByReplacingOccurrencesOfString:#"\\\"" withString:#"'"];
then use this formattedString.
I have investigates your json file from Json formatter & Validator, there are lots of error in your json file, so first check your file from this validator and this formatter gives you error with description. Re-build your json file, if you still getting any problem then ask.
I upload the json string to the server like
NSDictionary *values = [[NSDictionary alloc]initWithObjectsAndKeys:#"name", #"objective", nil];
NSArray *array = [[NSArray alloc]initWithObjects:values,nil];
NSDictionary *result = [[NSDictionary alloc]initWithObjectsAndKeys:array, #"objectives", nil];
I use the following code to convert the dictionary to JSON:
id obj = result;
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:kNilOptions error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
I get correct json like
{ "objectives":[
{"objective":"name"}
]
}
This is correct json but I need json string like
{ objectives:[
{"objective":"name"}]
}
Is it possible to create without double quotes in key in iOS?
Only this json string we get the response otherwise I get error.
if it is only the first key that you want to remove quotes from, you can use the following quick workaround
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\"objectives\"" withString:#"objectives"]];
I want to parse those Json that has a structure like this on iOS, with SBJSon libs
Can anyone help me? thanks so much!
{"error":{"username":["The username has already been taken."],"email":["The email has already been taken."]}}
NSString *str=#"{\"error\":{\"username\":[\"The username has already been taken.\"],\"email\":[\"The email has already been taken.\"]}}";
NSData *data=[str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: nil];
NSLog(#"dic is %#",json);
//output
dic is {
error = {
email = (
"The email has already been taken."
);
username = (
"The username has already been taken."
);
};
}
Using SBJSon
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [str JSONValue];
SBJsonParser * parser = [[SBJsonParser alloc] init];
NSObject * responseobj = [parser objectWithData:data]; // for NSData
NSObject * responseobj = [parser objectWithString:string]; // for NSString
In your case "responseobj" will be of type NSDictionary.
I am using RestKit 0.9.4. I would like to post a JSON that has a key that needs to be populated from an object's attribute.
The JSON is as follows:
{
"types":[ {
"1" : "value1"
},
{
"7" : "value2"
} ]
}
I have an object with 2 NSString data members named keytype and value respectively .
keytype is the variable that has the values that appear for the key in the nested json above ( "1", "7" etc above ). mapKeyOfNestedDictionaryToAttribute will probably not work here because the dynamic attribute( to be used as key) is at the inner most level..
Can this be posted using RestKit?
Here's how you make that structure in an NSDictionary, and then post it as JSON using RestKit. Also, the response then maps to a model.
// make the inner dictionaries (probably would use a for loop for this
NSDictionary *dict1 = [[NSDictionary alloc] initWithObjectsAndKeys:#"value1", #"1", nil];
NSDictionary *dict7 = [[NSDictionary alloc] initWithObjectsAndKeys:#"value2", #"7", nil];
// put them in an array
NSArray *types = [[NSArray alloc] initWithObjects:dict1, dict7, nil];
// now put the array in a dictionary
NSDictionary *finalDict = [[NSDictionary alloc] initWithObjectsAndKeys:types, #"types", nil];
// create a JSON string from your NSDictionary
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:finalDict
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
NSString *jsonString = [[NSString alloc] init];
if (!jsonData) {
NSLog(#"Got an error: %#", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
// make the post using the objectManager if you want to map the response to a model
RKObjectManager* objectManager = [RKObjectManager sharedManager];
[objectManager loadObjectsAtResourcePath:#"/api/" delegate:self block:^(RKObjectLoader* loader) {
loader.serializationMIMEType = RKMIMETypeJSON; // We want to send this request as JSON
loader.objectMapping = [objectManager.mappingProvider objectMappingForClass:[Plan class]];
loader.resourcePath = #"/api/";
loader.method = RKRequestMethodPOST;
loader.params = [RKRequestSerialization serializationWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON];
}];