Get data from subarray JSON IOS - ios

I have a json array like this:
"posts": [
{
"id": 917,
"tags": [
{
"id": 39
}
]
},
{
"id": 918,
"tags": [
{
"id": 38
}
]
}
]
I've already get post id, but can't get the post tags id
Need to get data for each post, ex. Post 917 (tag 39), Post 918 (tag 38).
I use the Jsonloader from github, link: github.com/Phillipus/JSONHandler

I think the format for json is wrong. It should be something like:-
"posts":[{"id":917,"tags":39},{"id":918,"tags":38}]
This is an array of one 2 dictionary objects. Then, you can get the objects using
NSArray * postArray = [json objectForKey:#"posts"];
NSDictionary * firstObject = [postArray firstObject];
NSNumber * id1 = [firstObject objectForKey:#"id"];
NSArray * tags1 = [firstObject objectForKey:#"tags"];
NSNumber* tag1 = [[tags firstObject] objectForKey:#"id"];
Try this out.
Updated answer:
NSArray * postArray = [json objectForKey:#"posts"];
for(int i=0;i<postArray.count;i++){
NSDictionary * postObject = [postArray objectAtIndex:i];
NSNumber * postId = [postObject objectForKey:#"id"];
NSLog(#"PostID:%#",postId);
NSArray * postTag = [postObject objectForKey:#"tags"];
for(int j=0;j<postTag.count;j++){
NSDictionary * postTagIdDic = [postTag objectAtIndex:j];
NSNumber * postTagId = [postTagIdDic objectForKey:#"id"];
NSLog(#"postTagId:%#",postTagId);
}
}

you can use this
NSError *error=nil;
id json=[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (!error) {
NSLog(#"json:%#",json);
NSArray *a=[[json objectForKey:#"posts"] copy];
NSArray *tags=[[a objectAtIndex:0] copy];
NSLog(#"%#",[NSStrig stringWithFormat:#"%#",[[tags objectAtIndex:0] objectForKey:#"id"]]);
[a release];
}

Related

Get the values from JSON string using NSDictionary

How can i get values from the following JSON.
JSON
{
"X": [
{
"one": 1,
"two": "Bill"
},
{
"one": 2,
"two": "Hutch"
}
]
}
CODE
NSDictionary *dictionary = (NSDictionary *) responseObject;
dc =[dictionary objectForKey:#"X"];
Now how can i print the value of "one" and "two"
NB : dc is a NSMutableDictionary.
Use this code..
NSString *str = #"{\"X\":[{\"one\": 1, \"two\": \"Bill\" }, { \"one\": 2, \"two\": \"Hutch\" } ] }";
str = #"{\"X\":[{\"one\": 1,},{\"one\": 2,\"two\": \"Hutch\"}]}";
NSError *jsonError;
NSData *objectData = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"%#",[json objectForKey:#"X"]);
NSMutableDictionary *dict = [json objectForKey:#"X"];
for (NSDictionary *tempDict in dict) {
NSLog(#"%#",tempDict);
if ([tempDict objectForKey:#"one"]) {
NSLog(#"%#",[tempDict objectForKey:#"one"]);
}
if ([tempDict objectForKey:#"two"]){
NSLog(#"%#",[tempDict objectForKey:#"two"]);
}
}
Hope this helps you :)
See here is your JSON
{
"X": [
{
"one": 1,
"two": "Bill"
},
{
"one": 2,
"two": "Hutch"
}
] }
To get the second object from X array and in that value of "one" :
NSString *value = [[[dictionary objectForKey:#"X"] objectAtIndex: 1] objectForKey: #"one"];
Here is explanation into multiple line for the same code used above in single line:
NSArray *arr = [dictionary objectForKey:<Root Key String>]; // save data to array from dictionary
NSDictionary *dict = [arr objectAtIndex: <Index of object>]; // get the actual object from array based on index
NSString *resultString = [dict objectForKey: <Key String>]; // get value of your required key

Parsing values from NSArray based on JSON format

I have a NSArray which is based on JSON format. I requested it from the web and saved it in the array. I am trying to use a dictionary to get the values of "categoryname" and "subscore" and store them in new arrays, but they remain empty. Do I have to convert the array back to NSData using JSON serialisation or is there a more direct way to achieve this?
NSArray detailedscore:
{
"articles": [
{
"abstract": "text",
"title": "title"
}
],
"subscore": 3,
"categoryname": "Reporting"
},
{
"articles": [
{
"abstract": "text2",
"title": "title"
}
],
"subscore": 1,
"categoryname": "Power"
}]
}
Code:
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores addObject:subscore];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
{} ----> means dictionary, []---> array..... this is a rule I follow while assinging the return value from webservices as NSArray or NSDictionary....
Depending on your current JSON format, perhaps this might give you an idea
NSMutableArray *categoryArray = [NSMutableArray new];
for (NSDictionary *childDict in self.detailedscore)
{
[categoryArray addObject:[childDict objectForkey:#"categoryname"]];
}
If you have the array use below code
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores score];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
The problem wasn't in the array or dictionary or the web request. I didn't allocated the NSMutableArrays so they were empty all the time. The code works fine for extracting values from the array in case anyone wants to use it.
Hope this helps.
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
NSLog(#"Dict %#",dict);
BOOL isValid = [NSJSONSerialization isValidJSONObject:dict];
if (isValid) {
[target getJSONFromresponseDictionary:dict forConnection:strTag error:connectionError];
}
else{
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[target getStringFromresponseDictionary:strResponse forConnection:strTag error:error];
}

How to access the my JSON in iOS

I'm newbie in iOS. And I'm having a problem accessing my JSON file that I retrieve in my web app server.
JSON:
{
"content": [
{
"info": [
{
"type": "TEL",
"label": "Call Phone",
"id": "32d7da39-39cc-4319-ab76-e67db9385722"
}
],
"name": "myname",
"title": "myname_title",
"image": "",
}
],
"timestamp": 1370491676,
"error": "SUCCESS"
}
I convert NSData to JSON :
NSMutableDictionary *mydatas =[NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
When I'm using this code to retrieve the name:
NSString *name = [[mydatas objectForKey:#"content"] objectForKey:#"name"];
It terminate the program.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x71e3240'
Include SBJSon Framework from here
NSString *responseString = [[NSString alloc]initWithData: urlData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",responseString);
NSDictionary * mydatas = [responseString JSONValue];
NSString *name = [[mydatas objectForKey:#"content"]objectForKey:#"name"];
content is an NSArray, not an NSDictionary. You need to use NSArray calls to retrieve the item in the array:
// Be sure to check that the array has at least one item or you'll throw an exception
NSArray *contentArray = [mydatas objectForKey:#"content"];
if ( contentArray.count > 0 ) {
NSString *image = [contentArray[0] objectForKey:#"name"];
}
Why you are not using the SBJSON framework . https://github.com/stig/json-framework/.
Then refer following SO question :How to parse JSON into Objective C - SBJSON . This will be easy for you to parse this data.
NSArray *contentArray = [mydatas objectForKey:#"content"];
[contentArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(#"name of content at index %i is == %#",idx,[obj valueForKey:#"name"]);
}];
By looking at your JSON I can say,
Your mydatas dictionary contains 3 keys which are content, timestamp, error
The object for key content is an array. If you want to retrieve the object for key name you need to do the following
if([[mydatas objectForKey:#"content"] count]>0)
{
NSString *name = [[[mydatas objectForKey:#"content"] objectAtIndex:0]objectForKey:#"name"];
}
This will work.
try like this,
NSString *name = [[[mydatas objectForKey:#"content"] objectAtIndex:0]objectForKey:#"name"];
Try This One
NSMutableDictionary *mydatas =[NSJSONSerialization JSONObjectWithData:urlData options:kNilOptions error:&error];
Save it to Array
NSArray *array = [mydatas objectForKey:#"content"];
for (int i=0; i<[array count]; i++) {
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:[[array objectAtIndex:i] valueForKey:#"info"] forKey:#"info"];
[someArray addObject:dic];
[typeArray addObject:[[dic valueForKey:#"info"] valueForKey:#"type"] valueForKey:#"name"]];
NSString * NameStr = [typeArray objectAtIndex:i];
NSLog(#"String For Name : %#",NameStr);
[dic release];
}
Hope its Work!!!!!!!!!!!

iOS JSon parsing, array in array

I have a simple json format with an array within an array, but I can't figure out how to get the inner array. How do I grab the "Commute" tag as an NSArray or a NSDictionary?
Here is my json:
{
"Language": "EN",
"Place": [
{
"City": "Stockholm",
"Name": "Slussen",
"Commute": [
"Subway",
"Bus"
]
},
{
"City": "Gothenburg",
"Name": "Central station",
"Commute": [
"Train",
"Bus"
]
}
]
}
Here is my code:
NSString *textPath = [[NSBundle mainBundle] pathForResource:#"Places" ofType:#"json"];
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPath encoding:NSUTF8StringEncoding error:&error]; //error checking omitted
NSData *jsonData = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
NSArray* AllPlaces = [json objectForKey:#"Place"];
for(int n = 0; n < [AllPlaces count]; n++)
{
PlaceItem* item = [[PlaceItem alloc]init];
NSDictionary* place = [AllPlaces objectAtIndex:n];
item.City = [place objectForKey:#"City"];
item.Name = [place objectForKey:#"Name"];
NSDictionary* commutes = [json objectForKey:#"Commute"];
[self.placeArray addObject:(item)];
}
Your code should be:
NSArray* commutes = [place objectForKey:#"Commute"];
Thwt would give back an array holding "Subway" and "Bus".
I think the problem is the access to json, it should be place instead:
NSArray* commutes = [place objectForKey:#"Commute"];
NSArray *commutes = [place objectForKey:#"Commute"];
This will give you an NSArray with "Subway" and "Bus".
You can considerably shrink you code using KVC Collection Operators:
NSArray *commutes = [json valueForKeyPath:#"Place.#distinctUnionOfArrays.Commute"];
If you want all repeated commutes use #unionOfArrays modifier.

How can I get the JSON array data from nsstring or byte in xcode 4.2?

I'm trying to get values from nsdata class and doesn't work.
here is my JSON data.
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
and here is my code
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(#"id = %#",[iTem objectForKey:#"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
return iTem;
}
how can I access every value in the JSON? Please help me.
look like this ..
NSString *jsonString = #"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:#"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:#"count"] integerValue]];
}
if ([dic objectForKey:#"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:#"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:#"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:#"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
I did it by using the framework : http://stig.github.com/json-framework/
It is very powerfull and can do incredible stuff !
Here how I use it to extract an item name from an HTTP request :
(where result is the JSO string)
NSString *result = request.responseString;
jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:#"wine_name"];
Hope this will be helpfull
Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.
NSArray *items = [iTem objectForKey:#"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];
Try JSONKit for this. Is is extremely simple to use.
Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial
There is no need to import any JSON framework. (+1 if this answer is relevant)

Resources