here is the JSON data that has multiple object i just want to parse "continueWatching" object so i just shared it:
{
"message": {
"continueWatching": [{
"id": "2",
"video": [{
"videoName": "fsfdsf",
"coverPicture": ""
}
],
"cursorPosition": "12:32:25",
"dateWatched": "2015-07-08 00:00:00",
"updated": "2015-07-15 12:12:34"
}, {
"id": "1",
"video": [{
"videoName": "Hello",
"coverPicture": ""
}
],
"cursorPosition": "15:42:41",
"dateWatched": "2015-07-02 00:00:00",
"updated": "2015-07-02 00:00:00"
}, {
"id": "3",
"video": [{
"videoName": "adfafadf",
"coverPicture": ""
}
],
"cursorPosition": "12:32:25",
"dateWatched": "2015-07-01 00:00:00",
"updated": "2015-07-02 00:00:00"
}]
}
My code right now, i printed the whole JSON data and the message object, i need to get all "videoName" in a single array arranged by their "id" numbers plus i also want to get all "cursorPosition" in a single array arranged by their "id"
NSString *myRequestString = [NSString stringWithFormat:#"getRecommendations=all&profileId=1"];
// Create Data from request
NSData *myRequestData = [NSData dataWithBytes: [myRequestString UTF8String] length: [myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: url];
// set Request Type
[request setHTTPMethod: #"POST"];
// Set content-type
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"content-type"];
// Set Request Body
[request setHTTPBody: myRequestData];
// Now send a request and get Response
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
// Log Response
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
NSLog(#"Response: %#",response);
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
BOOL boolean=[[dict objectForKey:#"boolean"]boolValue];
NSArray *message=[dict objectForKey:#"message"];
NSLog(#"kajhsdahfohofhoaehfpihjfpejwfp%#",message);
I do not get any very elegant way of doing this but this will solve your problem
NSArray *continueWatching = [[dict objectForKey:#"message"] objectForKey:#"continueWatching"];
//sort all objects using id.
NSSortDescriptor *sortDesc = [NSSortDescriptor sortDescriptorWithKey:#"id" ascending:YES selector:#selector(localizedStandardCompare:)];
continueWatching = [continueWatching sortedArrayUsingDescriptors:#[sortDesc]];
NSMutableArray *cursorPosition = [NSMutableArray array];
NSMutableArray *videoNames = [NSMutableArray array];
[continueWatching enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//find all videos array and then again enumerate it and extract all video names
NSArray *videos = [obj objectForKey:#"video"];
[videos enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[videoNames addObject:[obj objectForKey:#"videoName"]];
}];
//extract all curser positions and save them
[cursorPosition addObject:[obj objectForKey:#"cursorPosition"]];
}];
NSLog(#"%#",cursorPosition);
NSLog(#"%#",videoNames);
this solution uses valueForKeyPath to extract the requested objects without loops.
The array continueWatchingArray is sorted before getting the properties.
Therefore the resulting arrays videoNameArray and cursorPositionArray are sorted, too
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableLeaves error:nil];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:#"id" ascending:YES];
NSArray *continueWatchingArray = [[dict valueForKeyPath:#"message.continueWatching"] sortedArrayUsingDescriptors:#[sortDescriptor]];
NSArray *cursorPositionArray = [continueWatchingArray valueForKeyPath:#"cursorPosition"];
NSArray *videoNameArray = [continueWatchingArray valueForKeyPath:#"video.videoName"];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
// repeat loop to flatten the array
for (NSArray *subArray in videoNameArray) {
[tempArray addObject:subArray[0]];
}
videoNameArray = tempArray;
NSLog(#"%#", videoNameArray);
NSLog(#"%#", cursorPositionArray);
Your code will be like this.
NSArray* continueWatching = [[dict objectForKey:#"message"] objectForKey:#"continueWatching"];
continueWatching = [continueWatching sortedArrayUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"id" ascending:YES]]];
NSMutableArray *arrayOfVideos = [[NSMutableArray alloc]init];
NSMutableArray *arrayOfCursors = [[NSMutableArray alloc]init];
for(NSDictionary *dicData in continueWatching){
NSArray *videoArray = [dicData objectForKey:#"video"];
[arrayOfVideos addObjectsFromArray:videoArray];
[arrayOfCursors addObject:[dicData valueForKey:#"cursorPosition"]];
}
//now in the two arrays you will have the required result.
JSON object "message" is a dictionary and not an array.
NSDictionary *messages = [dict objectForKey:#"message"];
NSArray *continue = [messages objectForKey:#"continueWatching"];
You now have an array of your videos's properties.
NSSortDescriptor *sortDesc = [NSSortDecriptor sortDescriptorWithKey:#"id" ascending:YES];
NSArray *sortedVideosById = [continue sortedArrayUsingDescriptors:#[sortDesc]];
You now have an array of your videos's properties, sorted by video's id.
Parse it to collect video names and cursorPosition in arrays, sorted by ids.
NSMutableArray *videoNames = [NSMutableArray array];
NSMutableArray *cursorPositions = [NSMutableArray array];
for( NSDictionary *v in sortedVideosById )
{
NSArray *videoArray = (NSArray *)(v[#"video"]);
NSDictionary *firstVideo = videoArray[0];
videoNames addObject:firstVideo[#"videoName"];
[cursorPositions addObject:v[#"cursorPosition"];
}
Related
As a response to a request I get JSON:
{
"letters": {
"A": 0,
"B": 1,
"C": 2,
"D": 3,
"E": 4,
...
}
}
That's my code to acquire this JSON:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// Handle error
}];
I want to fill array with keys (not values) like this:
array[0] = "A"
array[1] = "B"
...?
NSMutableArray *parts = [NSMutableArray new];
NSDictionary *allletters = [responseObject objectForKey:#"letters"];
for (NSString *key in [allletters allKeys])
{
NSString *value = [allletters objectForKey: key];
[parts insertObject:key atIndex:[val intValue]];
}
I haven't tested the code. But it should be something similar to this:
NSDictionary *responseDictionary = (NSDictionary*)responseObject;
NSDictionary *letters = [responseDictionary objectForKey:"letters"];
NSMutableArray *lettersArray = [[NSMutableArray alloc]init];
if ( letters ){
for (NSInteger i = 0; i < letters; ++i)
{
[lettersArray addObject:[NSNull null]];
}
[letters enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id key, id object, BOOL *stop) {
[lettersArray replaceObjectAtIndex:[key integerValue] withObject:object]
}]
}
try the following code
NSDictionary *letters = [responseObject objectForKey:"letters"];
NSArray *lettersArray = [letters allKeys];
As you are already using the JSON response serializer, responseObject should be a dictionary.
To get all keys of the sub dictionary letters, do
NSArray *letters = [reponseObject[#"letters"] allKeys];
No need for a mutable array here. But if you want it mutable , do
NSMutableArray *letters = [[reponseObject[#"letters"] allKeys] mutableCopy];
i am newbie in iOS Development. i want to parse my this JSON Data into to array First array Contain all Data and Second array Contain only -demopage: array Value.
status: "success",
-data: [
{
mid: "5",
name: "October 2014",
front_image: "http://www.truemanindiamagazine.com/webservice/magazineimage/frontimage/01.jpg",
title: "October 2014",
release_date: "2014-10-01",
short_description: "As the name suggest itself “Trueman India” will cover icons of India. Our national Magazine “Trueman India” is an expansion to our business, i",
current_issue: 0,
-demopage: [
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/01-1413806104.jpg",
page_no: "1"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/2-1413806131.jpg",
page_no: "2"
},
{
link: "http://www.truemanindiamagazine.com/webservice/magazineimage/pageimage/2014/10/3-1413806170.jpg",
page_no: "3"
}
]
}
]
Here my main Dictionary Key is data i want data keey value in my One array and demopage key value in to another array here my two Array is self.imageArray and self.imagesa here my code For that
- (void)viewDidLoad
{
[super viewDidLoad];
[self.collectionView registerNib:[UINib nibWithNibName:#"CustumCell" bundle:nil] forCellWithReuseIdentifier:#"CellIdentifier"];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: imgURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
-(void)fetchedData:(NSData *)responsedata
{
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
if (responsedata.length > 0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.imageArray addObjectsFromArray:arr];
[self.storeTable reloadData];
}
self.storeTable.hidden=FALSE;
for (index=0; index<[self.imageArray count]; index++)
{
for(NSDictionary *dict in self.imageArray)
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
NSLog(#"New Demo page array %#",self.imagesa);
}
}
then i get my data key value and it is ok but i got only last index means here my -data key Contain three -demopage key and i get only last -demopage key value i want all -demopage key value in to self.imagesa please give me solution for that.
also my Webservices link is Link
First get -data in NSMutableArray.
NSMutableArray *dataArray = [[NSMutableArray alloc]init];
NSMutableArray *imagesArray = [[NSMutableArray alloc]init];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
dataArray=[json objectForKey:#"data"];
for(NSDictionary *dict in dataArray )
{
imagesArray = [dict valueForKey:#"demopage"];
self.imagesa = imagesArray;
}
[selt.tableView reloadData];
You can give it a try like this:
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
NSDictionary *dataDict = [json objectForKey:#"data"];
NSArray *imageArray = [dataDict objectForKey:#"demopage"];
self.imagesa = [NSMutableArray array];
for (NSDictionary *dict in array) {
NSString *imageUrl = [dict objectForKey:#"link"];
[self.imagesa addObject:imageUrl];
}
Then you got imageArray as dataSource for the collectionView.
I would use SBJson library, but not the last 4th version:
pod 'SBJson', '3.2'
Sample code, I changed variable names and formatting a little bit:
// Create a JSON String from NSData
NSData *responseData = [NSData new]; // Here you should use your responseData
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if (! jsonString ) {
// Handle errors
}
// Create SBJsonParser instance
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
// Parse JSON String to dictionary
NSDictionary *jsonDic = [jsonParser objectWithString:jsonString];
// Get an array by key
NSArray *dicArray = [jsonDic objectForKey:#"demopage"];
// Reload collection view
if ( [dicArray count] > 0 ) {
dispatch_async(dispatch_get_main_queue(), ^{
// Reload Your Collection View Here and use dicArray (in your case imagesa array with dictionaries)
});
}
And when you set a cell, you can use something like this:
NSDictionary *dic = dicArray[indexPath.row];
NSString *link = dic[#"link"];
NSString *pageNo = dic[#"page_no"];
I need to get Particular Object values ( A, B, C, D) and related key values (#"name" ). Here below I have posted my sample code and response. Please help me.
NSString *combined = URL;
NSURL *url = [[NSURL alloc] initWithString:combined];
NSData *responseData=[NSData dataWithContentsOfURL:url];
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray *responsData = [jsonDictionary objectForKey:#"response"];
// GET A,B,C Object values
NSDictionary *d1 = responsData.firstObject;
NSEnumerator *enum1 = d1.keyEnumerator;
NSArray *firstObject = [enum1 allObjects];
My JSON Response :
response : [ {
A = [ {
name : tango
}
{
name : ping
}
]
B = [ {
name : tango
}
{
name : ping
}
]
} ]
You can achieve the list of all names using this:
NSMutableArray *names = [[NSMutableArray alloc] init];
for (NSDictionary *dict in responsData) {
[dict enumerateKeysAndObjectsUsingBlock: ^(id key, id obj, BOOL *stop) {
NSArray *valueArray = (NSArray *)obj;
for (NSDictionary * namesDict in valueArray) {
[names addObject:namesDict[#"name"]];
}
}];
}
Output:
NSLog(#"Names %#",names);
tango, ping, tango, ping.
Hope that helps!
Simply
for(NSDictionary *dict in firstObject){
NSLog(#"%#",[dict objectForKey:#"name"]);
}
i just get started with Ios programming, and i have to parse a nested Json file and extract the items and lables, the problem is i have to display the list of the items on a tableview and refresh my tableview everytime i click on a row of my table view:
i did display the first list of my items but i'm trying to display my nested items and display them on my "new" tableview:
here are a simple of my JSON code and my objective-c code:
"results": {
"items": [
{
"id": "0100",
"label": "Actualités",
"cover": "http://XXXX_01.jpg",
"coverFrom": "XXX-03",
"coverTo": "2031-CCC18",
"coverOrder": 1,
"items": [
{
"id": "0101",
"label": "Actualité / Infos",
"cover": "http://XXXX.jpg",
"coverFrom": "2014XXX-24",
"coverTo": "2031-XXXX18",
"coverOrder": 1,
"items": [
]
},
and my RootViewContoller contain this code of the function connectionDidFinishiongLoading**
// we will follow the format of our nested JSON
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:dataRequest options:0 error:nil];
NSDictionary *results = [allDataDictionary objectForKey:#"results"];
NSArray *arrayOfItems = [results objectForKey:#"items"];
for (NSDictionary *diction in arrayOfItems) {
//NSArray *ide = [diction objectForKey:#"id"];
NSString *label = [diction objectForKey:#"label"];
// add new object founded
[array addObject:label];
}
// reload my tableview
[[self tableView]reloadData];
// myParsingResults = [NSJSONSerialization JSONObjectWithData:dataRequest options:nil error:nil];
[[self tableView]reloadData];
If I understood correctly, try something like that:
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:dataRequest options:0 error:nil];
NSDictionary *results = [allDataDictionary objectForKey:#"results"];
NSArray *array = [results objectForKey:#"items"];
NSMutableArray *arrayLabels = [[NSMutableArray alloc] init];
NSDictionnary *dicoTemp = [array objectAtIndex:0];
while([dicoTemp objectForKey:#"items"])
{
arrayLabels addObject:[[dicoTemp objectForKey:#"items"] objectForKey:#"label"];
NSArray *arrayTemp = [dicoTemp objectForKey:#"items"];
dicoTemp = [arrayTemp objectAtIndex:0]; //I don't know how you JSON ends, you may have to check if [arrayTemp count] > 0. I presumed that at the end, there was no object for key "items"
}
[[self tableView] reloadData];
That a weird nested JSON response, in my opinion.
Try this one...
NSError *error = nil;
NSURL *Url = [[NSURL alloc] initWithString:#"Your URL"];
jsonData = [NSData dataWithContentsOfURL:Url options:NSDataReadingUncached error:&error];
if(jsonData==Nil){
UIAlertView * alert=[[UIAlertView alloc]initWithTitle:#"Error" message:#"Please check your internet connection" delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:#"ok", nil];
[alert show];
}
else{
NSDictionary *dataDictionary =[[NSDictionary alloc]init];
dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
[array addObject:[[[dataDictionary objectForKey:#"results"] valueForKey:#"items"] valueForKey:#"label"]];
}
and reloads your tableview.
I am new in the iOS development and i am calling the web service that returns me data like
[
{
"ID": "3416a75f4cea9109507cacd8e2f2aefc3416a75f4cea9109507cacd8e2f2aefc",
"Name": "2M Enerji"
},
{
"ID": "072b030ba126b2f4b2374f342be9ed44072b030ba126b2f4b2374f342be9ed44",
"Name": "Çedaş"
},
{
"ID": "093f65e080a295f8076b1c5722a46aa2093f65e080a295f8076b1c5722a46aa2",
"Name": "Çelikler"
},
{
"ID": "7cbbc409ec990f19c78c75bd1e06f2157cbbc409ec990f19c78c75bd1e06f215",
"Name": "Çoruh EDAŞ"
},
{
"ID": "70efdf2ec9b086079795c442636b55fb70efdf2ec9b086079795c442636b55fb",
"Name": "İçdaş"
}
]
Now i am trying to get it in the array , the array will be seperate for the name and id , i am done till taking in NSDICT following is my code
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"finish loading");
NSString *loginStatus = [[NSString alloc] initWithBytes:[webData mutableBytes]
length:[webData length]
encoding:NSUTF8StringEncoding];
NSString *responsewith = [[NSString alloc] initWithData:webData
encoding:NSUTF8StringEncoding];
//providerData = [NSKeyedUnarchiver unarchiveObjectWithData:webData];
providerDropData = [NSString stringWithFormat:responsewith];
NSLog(#"drop %#",providerDropData);
NSArray *providerData = [providerDropData valueForKey:#"ID"];
NSLog(#"jey %#",responsewith);
NSLog(#"resonser %#",responsewith);
NSLog(#"laoding data %#",loginStatus);
//greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
When i tried saving the NSDictionary to the NSArray for #"ID" the application get crashed.
Please help
You simply want to use NSJSONSerialization
NSError *error = nil;
NSArray *results = [NSJSONSerialization JSONObjectWithData:webData options:0 error:&error];
if (!results)
NSLog(#"%s: JSONObjectWithData error: %#", __FUNCTION__, error);
// get the first provider id
NSString *providerData = results[0][#"ID"];
You can fetch data from JSON like below way as well,
id jsonObjectData = [NSJSONSerialization JSONObjectWithData:webData error:&error];
if(jsonObjectData){
NSMutableArray *idArray = [jsonObjectData mutableArrayValueForKeyPath:#"ID"];
NSMutableArray *nameArray = [jsonObjectData mutableArrayValueForKeyPath:#"Name"];
}
Convert the data to NSDictionary by parsing, then you can extract using KVP.
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSDictionary * providerDropData = [NSJSONSerialization JSONObjectWithData:webData error:&error];
NSLog(#"drop %#",providerDropData);
NSMutableArray *providerData = [NSMutableArray new];
NSString *key = #"ID";
for (key in providerDropData){
NSLog(#"Key: %#, Value %#", key, [providerDropData objectForKey: key]);
[providerData addObject:[providerDropData objectForKey:key]];
}
NSLog("ID Array = %#", providerData]);
}