How to POST NSArray values in JSON or Is there any possible to POST JSON values.
I thing this is useful, otherwise I modify something in code
NSMutableArray * arr = [[NSMutableArray alloc] init];
// assume that this is your Array
[arr addObject:#"1"];
[arr addObject:#"2"];
// convert the NSArray to NSdata , the reason is always the web service get string only
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
// finally append the -- jsonString to your web service
Related
I try to convert this dictionary but I get a error.
NSException * name: #"NSInvalidArgumentException" - reason: #"***
+[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write" 0x000060000044dda0
NSMutableDictionary *clientinfo = [[ NSMutableDictionary alloc] init];
[clientinfo setObject:remittance.cliente.cliente_id forKey:ST_clientID];
NSMutableDictionary *country = [[ NSMutableDictionary alloc] init];
[country setObject:remittance.pais.paisID forKey:ST_countryID];
NSMutableDictionary *remittancedata = [[ NSMutableDictionary alloc] init];
[remittancedata setObject:remittance.nroIdentificacion forKey:ST_noidentification];
[remittancedata setObject:clientinfo forKey:ST_client];
[remittancedata setObject:country forKey:ST_country];
NSError *err = nil;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:remittance options:0 error:&err];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
An issue like this occurs if one or more of your value or key types can't be serialized.
Here are the supported types.
In case you have incompatible types, you need to convert them yourself first (often to a string representation).
You were serialising an object which was your custom object which doesn't support in JSON. You need to serialise either a NSDictionary or NSArray into JSON.
NSData * jsonData = [NSJSONSerialization dataWithJSONObject: remittancedata options:0 error:&err];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
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);
As the question says, I get an unexpected output when importing JSON into a TableView class.
JSON:
{"city":"Cambridge"}{"city":"Oxford"}
Objective-C:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.domain.com/cities.php"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSLog(#"%#", response);
Output:
<7b226369 7479223a 2243616d 62726964 6765227d 7b226369 7479223a 224f7866 6f726422 7d>
Fairly sure I'm structuring my JSON wrongly...
Your response is of NSData type and needs to be converted to a string.
NSString *responseString = [[NSString alloc] initWithBytes:[response bytes] length:[response length] encoding:NSUTF8StringEncoding];
NSLog(responseString);
You can also use the initWithData as described elsewhere
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
While this is useful for debugging, to actually extract or work with the data, you will want to convert it to dictionary or array.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:NULL];
From here, you can reference items in the dictionary.
NSArray *responseArray = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:nil];
NSLog(#"%#",responseArray);
NSMutableArray *cityArray =[[NSMutableArray alloc] init];
for (int i=0; i<[responseArray count]; i++)
{
[cityArray addObject:[NSString stringWithFormat:#"%#",[[responseArray objectAtIndex:i] valueForKey:#"city"];
}
Please note that, I believe you would fix that json and make it to json returning an array.
NSString *jsonStr = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsonStr);
What i need
"sampleId":"[{\"TextVal\":\"10233\"}]"
Where i have
NSDictionary *sampledict=#{#"TextVal": #"10233"};
NSArray *arr=[NSArray arrayWithObject:sampledict];
[dict setObject:arr forKey:#"sampleId"];
But converting this to json text gives me
"sampleId":[{TextVal:10233}]
is there a way to get the value as {\"TextVal\":\"10233\"}?
This is for a web service call with POST data with following content.And the web service gives me Bad request error when excluding this \ .hence the requirement
Please note i am using AFNetworking for the purpose of network data fetch
That looks like "nested JSON". You have to create JSON data for the array
arr first, and put that into the outer dictionary. Then create JSON data for the complete
object:
NSDictionary *sampledict = #{#"TextVal": #"10233"};
NSArray *arr = [NSArray arrayWithObject:sampledict];
NSData *innerJson = [NSJSONSerialization dataWithJSONObject:arr options:0 error:NULL];
NSString *innerJsonString = [[NSString alloc] initWithData:innerJson encoding:NSUTF8StringEncoding];
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:innerJsonString forKey:#"sampleId"];
NSData *json = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
Output:
{"sampleId":"[{\"TextVal\":\"10233\"}]"}
I am converting my array to json object, then sending it to server. But It is showing some invalid characters when i get them in server end. like '\n', & '\'.
Here is a sample of my data which i get at the server end:
('[\n "{\\"id\\":2,\\"qrCode\\":\\"KdcUfeddHpbepeXnyiKFjcfedHp\\",\\"activity\\":\\"2\\",\\"time\\":\\"64485\\",\\"image_base64\\":\\"\\/9j\\/4AAQSkZJRgABAQAA"}"\n]');
But it should look like the following:
('[{"id":2,"qrCode":"KdcUfeddHpbepeXnyiKFjcfedHp","activity":2,"time":1372757846,"image_base64":"AA\\u003d\\u003d\\n"}]');
here is the code:
-(void)setOflynData2JsonFormat{
if (!([self.getOfflineData count] == 0)) {
NSArray *array = [self getOfflineData];
for (int i = 0; i<[array count]; i++) {
uniqueId++;
NSNumber *uId = [NSNumber numberWithInt:uniqueId];
OfflineTableObject *offObj = [array objectAtIndex:i];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:uId forKey:#"id"];
[dict setValue:offObj.qrCode forKey:#"qrCode"];
[dict setValue:offObj.offlineStatus forKey:#"activity"];
[dict setValue:offObj.time forKey:#"time"];
[dict setValue:offObj.imageData forKey:#"image_base64"];
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *singleJsonString = [jsonWriter stringWithObject:dict];
NSLog(#"Json string : %#",singleJsonString);
arrayOfJsonString = [[NSMutableArray alloc]init];
[arrayOfJsonString addObject:singleJsonString];
}
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithData:jsonDataFromArray encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%#", jsonString);
int check = [obj sendOfflynData2Server:jsonString];
}
}
So, where is the problem? Thnaks in advance for the help.
The problem is that you are translating your data to JSON twice.
You first translate all your dicts to json with
NSString *singleJsonString = [jsonWriter stringWithObject:dict];
add them to an array, and then re-translate the array to JSON with
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];
So instead of producing the expected JSON output, it serialize an array of JSON strings, hence the escaping mess.
Instead, you should just add your dicts to the array, and then serialize the whole thing :
arrayOfJsonString = [[NSMutableArray alloc]init];
for (int i = 0; i<[array count]; i++) {
// snip
[arrayOfJsonString addObject:dict];
}
NSData *jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString options:NSJSONWritingPrettyPrinted error:nil];