Issue in parsing NSDictionay into JSON NSData - ios

How do we convert a NSDictionary into JSON data object? I want to send a JSON data to my server. I am using the below code but facing an issue when it comes to NSDictionary containing Array or further NSDictionary in it. This works well with simple key-value pair.
Issue: It fails on the below line and sets the error object. This works fine if I remove arrays and dictionaries from the source myData dictionary.
NSData *aPostBodyData = [NSJSONSerialization dataWithJSONObject:myData options:0 error:&error];
Where myData looks like:
{
URI = "www.google.com";
addOnTestString = "4,3,";
status = (
"In Progress",
Submitted,
Delivered
);
data =
{
URI = "www.test.com";
testString = "43";
status = (
"In Progress",
Submitted,
Delivered
);
}
}
Error trace:

ok i just write a sample code that includes your situation and it works well.
NSArray * myarray=#[#"a",#"b"];
NSMutableDictionary * dict=[[NSMutableDictionary alloc] initWithObjects:#[#"a",myarray] forKeys:#[#"str",#"arr" ]];
NSData * js=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString * jsString=[[NSString alloc] initWithData:js encoding:NSUTF8StringEncoding];
NSLog(#"%#",jsString);
probable reasons for you get errors may be;
your myData is not in type NSDictionary or NSArray.
or while adding arrays to dictionary you are missing a point.

Related

how to send an array as a parameter to json service in iOS

I am using iPhone JSON Web Service based app.I need to pass input parameter as an array to a JSON web Service, how can I do this?
Array Contains 12 elements.
Here am providing sample service...
input parametes for this service:
dev_id = 1;
dev_name= josh and array items (projectslist,companyidentifier)
http://www.jyoshna.com/api/developer.php?dev_id=1&dev_name=josh&(Here i need to pass the array elements)
can any help us how to pass array as a input parameter to the json service?
First you have to convert array as JSON string
NSString *requestString=[jsonParser stringWithObject:array];
convert string to data
NSData *data=[requestString dataUsingEncoding:NSUTF8StringEncoding];
set that data as request Body
[request setHTTPBody:data];
You have to serialize the array and pass as an argument. Dont forget to unserialize in server side
you will need to create an NSMutabelDictionary of your array then JSON encode it, you can then send the resulting string you your webservice however you choose. I tend to build a POST request and send it that way
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];
NSMutableDictionary *tagData = [[NSMutableDictionary alloc] init];
for(int i = 0; i < array.count; i++)
{
NSString *keyString = [NSString stringWithFormat:#"key%i", i];
[tagData setObject:[array objectAtIndex:i] forKey:keyString];
}
[jsonDict setObject:tagData forKey:#"entries"];
NSData* data = [NSJSONSerialization dataWithJSONObject:jsonDict
options:NSJSONWritingPrettyPrinted error:&error];
NSString* aStr;
aStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
It is the sgtring aStr that you need to send

Fill NSDictionary with JSON [duplicate]

This question already has answers here:
Decode JSON to NSArray or NSDictionary
(5 answers)
Closed 9 years ago.
Iam new in iOS development .
I want to fill this json
"{
"form_name":"login_form_mobile",
"user_login":"mark wallet",
"password":"123456",
"dispatch":{"auth.login":"Sign in"}
}
"
into a NSDictionary to use it in post for a URL using AFNetworking.
I fill the dictionary like this
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:#"login_form_mobile",#"form_name",#"markwallet",#"user_login",#"123456",#"password",#"{ \" auth.login \" : \" Sign in \" }",#"dispatch", nil];
Now i have two problems
1-The \" in before and after auth.login is shown as it i want to show the Double quotes only.
BTW i tried to make a nested Dictionary this solved the first problem but for the second one problem not.
2-When i run the app. and see how the dictionary is filled it is shown like this
{
dispatch = "{ \" auth.login \" : \" Sign in \" }";
"form_name" = "login_form_mobile";
password = 123456;
"user_login" = markwallet;
}
a-There is equal between the key and its value and i need it : not =
b-some words doesnt have "" like password , 123456 and markwallet . i dont know why
c-Also i dont know why dispatch and it value go in the first.
EDIT:
I used this new code.
NSDictionary *dic = [[NSDictionary alloc]initWithObjectsAndKeys:#"Sign in",#"auth.login", nil];
NSArray *keys = [NSArray arrayWithObjects:#"form_name",#"user_login",#"password",#"dispatch",nil];
NSArray *objects = [NSArray arrayWithObjects:#"login_form_mobile",#"markwalletz",#"123456",dic,nil];
NSMutableDictionary * params1 = [[NSMutableDictionary alloc]init];
params1 = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
But when i see params1 value in the debug
{
dispatch = {
"auth.login" = "Sign in";
};
"form_name" = "login_form_mobile";
password = 123456;
"user_login" = markwalletz; }
And this is differs from the one i need as stated at the top of the question
And when i send a request with this dictionary it replies BAD Request.
Several things you need to understand:
When you NSLog an NSDictionary, it does not display JSON syntax. Yes, it superficially looks like JSON, but, as you noted, not all character strings are quoted (only those with blanks or odd characters get quotes) and an = is used instead of :. This is because it's a description of the NSDictionary object, not a JSON translation.
And, on the other hand, just because stuff looks the same between JSON and an NSDictionary does not make it the same. Your "dispatch":{"auth.login":"Sign in"} entry represents a second NSDictonary as the value of the key "dispatch". You cannot create that second dictionary simply by making the characters look like the JSON/description representation. Rather, you have to (as a separate conceptual step) create that one-element dictionary and then insert it as an object in the outer dictionary.
One place where NSDictionary and JSON are the same is that neither an NSDictionary nor a JSON "object" maintains the order of the key/value pairs it contains. So don't expect to see the values in the same order in one version vs the other.
Look at the NSJSONSerialization class. Methods in this class will convert JSON into the appropriate objects (e.g NSDictionary, NSArray), and vice versa. See the Apple Documentation for details.
Added:
For example:
NSString *jsonString = ... // Whatever your JSON is
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *d = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
What you get is a dictionary, d, that contains all the keys and their values as described in the JSON (assuming the JSON represented a dictionary). JSON data can represent an array of objects too. It's all quite flexible. I suggest reading the references documentation and search here for other examples using NSJSONSerialization. There are surely some good ones.
The "jsonString" variable should be formed like:
NSString *jsonString = #"{\"form_name\":\"login_form_mobile\",\"user_login\":\"mark wallet\",\"password\":\"123456\",\"dispatch\":\{\"auth.login\":\"Sign in\"}}";
Then, using the code above:
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSLog(#"DIC %#",dic);
will output:
DIC {
dispatch = {
"auth.login" = "Sign in";
};
"form_name" = "login_form_mobile";
password = 123456;
"user_login" = "mark wallet";
}
If your json string is in a NSString variable called "jsonString":
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
So your "dic" variable will have the parsed json.

ios - how do I extract a string from another string which is in JSON format?

I have an NSString like this:
[{"comment":"I am just weighing the idea."}]
How do I make it into a JSON object and get the value of the comment key?
Thanks!
You can use iOS's NSJSONSerialization object to get an object graph from JSON string/data. That API expects an NSData, so first you'll need to put the string into one.
NSData * jsonData = [myString dataUsingEncoding:NSUTF8StringEncoding];
NSArray * root = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:NULL];
NSString * comment = [[root objectAtIndex:0] objectForKey:#"comment"];
After processing, that root object should be an array or dictionary. In your case, it's clearly an array containing a dictionary.

Adding a JSON blob to a JSON request in iOS

I need to be able to create a JSON object (I'm using the built in classes in iOS 5).
The JSON that should be sent is this:
{"request_type":"<the request type (a string)>" "security_level":<the security level (an int)> "device_type":"<android or ios (a string)" "version":<the app version (android, ios on different version schemes) (a float)> "email":<the email address of the user sending the request (a string)> "blob":{<the contents of the actual request, encrypted/encoded according to the security level (a map)>}
My problem is with the last portion, a "blob"
Which is basically just another JSON object, i.e.
{"display_name":"Jack Bower", "email":"jackb#gmail.com", "password":"roflcopter"}
(Let's forget the password is in plaintext)
I can create everything using NSDictionary,
I just don't know how to add the last part.
My guess is create the first request using NSDictionary.
Then create the second blob request using another NSDictionary.
And then just add that second blob NSDictionary as a object back to the initial NSDictionary.
Will NSJSONSerialization understand what I'm trying to do?
Ok I think it's 5am and I'm just being really stupid:
here's the answer:
NSDictionary *blobData = [NSDictionary dictionaryWithObjectsAndKeys:
#"email",userEmail,
#"password",userPassword,
nil];
NSString *blobString = [[NSString alloc]
initWithData:[NSJSONSerialization dataWithJSONObject:blobData options:kNilOptions error:&error]
encoding:NSUTF8StringEncoding];
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
#"login",#"request_type",
0,#"security_level",
#"ios",#"device_type",
#"blob",blobString,
nil];
NSData *JSONRequestData = NULL;
if ([NSJSONSerialization isValidJSONObject:requestData]) {
NSData *JSONRequestData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error];
}
else NSLog(#"requestData was not a proper JSON object");

Understand and use this JSON data in iOS

I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];

Resources