how to access value json object in objective c - ios

I have a json file that is down code:
{"fileContent":[{"name":"directorffdsgfg","type":"file","ext":"sql","modified":"2013\/04\/11 - 10:00","created":"2013\/04\/11 - 10:00","size":"1577"},{"name":"directory02","type":"file","ext":"sql","modified":"2013\/04\/11 - 12:10","created":"2013\/04\/11 - 12:10","size":"1577"},{"name":"jquery-mousewheel-master","type":"file","ext":"zip","modified":"2013\/04\/11 - 12:10","created":"2013\/04\/11 - 12:10","size":"5213"}],"folderContent":[{"name":"Folder 2","type":"folder","ext":"sql","modified":"2013\/04\/11 - 05:04","created":"2013\/04\/11 - 05:04","size":"1577"},{"name":"Folder 1","type":"folder","ext":"zip","modified":"2013\/04\/15 - 09:08","created":"2013\/04\/15 - 09:08","size":"11867"}],"files":9,"folders":2}
I want to know that what access value in object json. (for example I want access to value of files , folders , fileContent , folderContent)
I dont know about it.

JSON is a dictionary, and you can use NSJSONSerialization to convert this string to a dictionary:
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
then you can access properties by key, so to get the folder content array:
NSArray *folderContent = [json objectForKey:#"folderContent"];

Related

Html tag in json object

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

Creating a json object dynamically

I have to make json request of following type.
{
"documents": [
{
"file_size": 48597,
"file_name": "pisa-en.pdf",
"file_content": "base64String"
}
]
}
Following is the way how im creating the json.
NSString *json = [NSString stringWithFormat:#"{\"documents\": [ { \"file_size\": %#, \"file_name\": %#\", \"file_content\": \"%#\" } ]}",_imageSizeArray[0],_imageNameArray[0],_baseArray[0]];
but the problem is that, the documents array may even contain more than one json object within it. If thats the case How can i create a jsonobject dynamically and embed it within documents array?
You have to take Array and add document object in that array
than at request time you have to convert your array to json string by following code
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myArray options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

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.

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