try to convert nsdictionary to json, the json have two object inside - ios

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];

Related

JSON Parsing: NSArray POST

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

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);

How to JSON encode arrays in array from iOS to PHP

I try to JSON encode NSDictionary into NSArray upload to PHP web-services.
This is how I JSON encode my NSArray:
NSError * error;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:my_array_1 options:0 error:&error];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByReplacingOccurrencesOfString:#"\"" withString:#"\\\""];
Then I insert this JSON String into another array by:
NSString * jsonRequest = [NSString stringWithFormat: #"{\"request\":\"syncBookmark\",\"bookmark_array\":\"%#\",\"user_id\":\"%#\"}", jsonString, user_id, nil];
NSData * requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
Before I request the webservices, the JSON encoded string is like:
{"request":"syncBookmark","bookmark_array":"[{\"PostId\":\"4\",\"last_edit_date\":\"2014-03-03 01:05:37\",\"BookmarkId\":\"1\",\"last_sync_date\":\"\",\"is_active\":\"1\"}]","user_id":"7"}
I can echo the 'user_id' in PHP which is '7' correctly, but when I check the array - is_array($bookmark_array) in PHP it just return FALSE. Am I doing the way wrongly to put arrays in array?
This is because you enter JSON string as string and it is obviously escaped by the stringWithFormat method.
You should create a NSDictionary and serialize that together. So instead of serializing my_array_1 variable, you will serialize the dictionary.
Create the dictionary:
NSDictionary* dictionary = #{ #"request" : #"syncBookmark", #"bookmark_array" : my_array_1 };
Then serialize the dictionary:
NSError * error;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString * jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
This is the correct way to serialize a JSON object, not inserting serialized objects into another string. Although I see why you wanted to do that.
Don't bother doing the stringByReplacingOccurrencesOfString stuff. Let NSJSONSerialization do all of the necessary quoting for you.
So, if you really need that jsonString as a string that your PHP will recursively un-encode, just JSON encode the array, and then put that in another dictionary and then encode that again:
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:my_array_1 options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSDictionary *dictionary = #{#"request" : #"syncBookmark",
#"bookmark_array" : jsonString,
#"user_id" : user_id};
NSData *finalData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
That should create a payload much like you said you wanted in your question.
Having said that, a more logical approach would be:
NSError *error;
NSDictionary *dictionary = #{#"request" : #"syncBookmark",
#"bookmark_array" : my_array_1,
#"user_id" : user_id};
NSData *finalData = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
If that's what generated your payload, then your PHP wouldn't have to do multiple calls to json_decode.

Conversion from object to json text ios

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\"}]"}

How to convert NSDictionary to NSString which contains json of NSDictionary?

How to convert NSDictionary to NSString which contains JSON of NSDictionary ?
I have tried like but without success
//parameters is NSDictionary
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
options:0
error:&error];
if jsonData is NSDictionary
NSString *str=[NSString stringWithFormat:#"json data is %#", jsonData];
OR if jsonData is NSData
NSString *str = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
If you just want to inspect it, you can create a NSString:
NSString *string = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
But if you're writing it to a file or sending it to a server, you can just use your NSData. The above construct is useful for examining the value for debugging purposes.

Resources