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.
Related
I have started on a new project. It is the first time that I see the following webservice output. This following json object text contains html tags.
I wonder how do you parse it to string or how do you know where the paragraph starts? or do you think that I should contact web service developer guy to fix this?
You can use
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e];
To turn the data into dictionary. Then you can access the value of "icerik" by traversing the dictionary tree with NSArray/NSDictionary. For your case example,
first nest is a dictionary of key "news" with array objects. So you get the the array out of it:
NSArray *newsArray = [JSON objectForKey:#"news"];
Then you get the first news item by getting another dictionary:
NSDictionary *firstNews = [newsArray objectAtIndex:0];
Then you can get icerik:
NSString *icerik = [firstNews objectForKey:#"icerik"];
Once you get the value as string, you need to do some string manipulation on it (many ways to do this)
You can get your html string as
NSDictionary *json = [NSJSONSerialization JSONObjectWithData: responseData options: NSJSONReadingMutableContainers error: &e];
NSString *icerik = json[#"news"][0][#"icerik"];
You can use UIWebView or UITextView to load html string.
NSString *myHTML = [NSString stringWithFormat:#"<html><body>%#</body></html>" ,icerik ];
[yourWebView loadHTMLString:myHTML baseURL:nil];
NSData* jsonData is the http response contains JSON data.
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonString: %#", jsonString);
I got the result:
{ "result": "\u8aaa" }
What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?
If you convert the JSON data
{ "result" : "\u8aaa" }
to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary
NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", jsonDict);
then you will get the output
{
result = "\U8aaa";
}
The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences
for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!
If you print the value of the key
NSLog(#"%#", [jsonDict objectForKey:#"result"]);
then you will get the expected output
說
I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…
NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …];
…and you should get the following dictionary back: #{#"result":#"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.
BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.
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.
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.
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"];