Apologies if this is a novice question, but I've been struggling to figure this out with no luck. I'm trying to pull a users' twitter timeline using the AFOAuth2Manager framework. Everything makes sense except the returned JSON object is an array and the entire object is one giant object. I obviously want to break it up into different elements and store them in a dictionary, but have not been able to figure it out so far.
This is a VERY partial example of what the array object looks like. The complete object is this with about 20 or so more tweets with this format attached. I will post the entire json object if requested, but it seems pretty pointless to post the entire thing.
Heres my code:
[manager GET:#"/1.1/statuses/user_timeline.json?screen_name=jack"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject ) {
self.object = responseObject;
NSLog(#"Success: %#", responseObject);
if ([responseObject isKindOfClass:[NSArray class]]) {
NSLog(#"object is a nsarray class");
} else if ([responseObject isKindOfClass:[NSDictionary class]]){
NSLog(#"object is a nsdictionary class");
} else {
NSLog(#"object is a different class");
}
NSArray *response = [NSArray arrayWithObject:responseObject];
NSLog(#"count %ld", [response count]);
NSData *dataFromTwitter = [NSKeyedArchiver archivedDataWithRootObject:self.object];
NSError *parseError = nil;
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
error:&parseError];
NSLog(#"response Dict: %#", responseDict);
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingAllowFragments
error:&e];
NSLog(#"jsonArray: %#", jsonArray);
NSError *jsonError2 = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
options:NSJSONReadingAllowFragments
error:&jsonError2];
if ([jsonObject isKindOfClass:[NSArray class]]) {
NSLog(#"its an array!");
NSArray *jsonArray = (NSArray *)jsonObject;
NSLog(#"jsonArray2 - %#",jsonArray);
}
else {
NSLog(#"its probably a dictionary");
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(#"jsonDictionary - %#",jsonDictionary);
NSLog(#"error %#", jsonError2);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", error);
}];
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Mon Feb 29 01:18:05 +0000 2016";
entities = {
hashtags = (
);
symbols = (
);
urls = (
);
"user_mentions" = (
{
id = 14616957;
"id_str" = 14616957;
indices = (
0,
7
);
name = "Jason Del Rey";
"screen_name" = DelRey;
},
{
id = 19040598;
"id_str" = 19040598;
indices = (
8,
18
);
name = "\U0ca0_\U0ca0";
"screen_name" = MikeIsaac;
},
{
id = 46063;
"id_str" = 46063;
indices = (
19,
30
);
name = "Hunter Walk";
"screen_name" = hunterwalk;
}
);
};
"favorite_count" = 12;
favorited = 0;
geo = "<null>";
id = 704113377920978944;
"id_str" = 704113377920978944;
"in_reply_to_screen_name" = DelRey;
"in_reply_to_status_id" = 704112911116013568;
"in_reply_to_status_id_str" = 704112911116013568;
"in_reply_to_user_id" = 14616957;
"in_reply_to_user_id_str" = 14616957;
"is_quote_status" = 0;
lang = en;
place = "<null>";
"retweet_count" = 0;
retweeted = 0;
source = "Twitter for iPhone";
text = "#DelRey #MikeIsaac #hunterwalk this changes everything";
truncated = 0;
user = {
"contributors_enabled" = 0;
"created_at" = "Tue Mar 21 20:50:14 +0000 2006";
"default_profile" = 0;
"default_profile_image" = 0;
description = "#withMalala!";
entities = {
description = {
urls = (
);
};
};
"favourites_count" = 11433;
"follow_request_sent" = "<null>";
"followers_count" = 3458722;
following = "<null>";
"friends_count" = 1859;
"geo_enabled" = 1;
"has_extended_profile" = 1;
id = 12;
"id_str" = 12;
"is_translation_enabled" = 0;
"is_translator" = 0;
lang = en;
"listed_count" = 25944;
location = "California, USA";
name = Jack;
notifications = "<null>";
"profile_background_color" = EBEBEB;
"profile_background_image_url" = "http://abs.twimg.com/images/themes/theme7/bg.gif";
"profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme7/bg.gif";
"profile_background_tile" = 0;
"profile_image_url" = "http://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
"profile_image_url_https" = "https://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
"profile_link_color" = 990000;
"profile_sidebar_border_color" = DFDFDF;
"profile_sidebar_fill_color" = F3F3F3;
"profile_text_color" = 333333;
"profile_use_background_image" = 1;
protected = 0;
"screen_name" = jack;
"statuses_count" = 19066;
"time_zone" = "Pacific Time (US & Canada)";
url = "<null>";
"utc_offset" = "-28800";
verified = 1;
};
},
You show no code in your question, in a comment you state you have a responseObject but not how you came by it.
The JSON you are getting from somewhere will be text, you may have it as an NSString, NSData, an NSArray whose elements are these, etc.
You need to obtain that text and then parse it as JSON, the NSJSONSerialization class will handle the parsing for you, the first line of its description states:
You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.
Once you have those Foundation objects - arrays, dictionaries, strings, numbers, etc. you can extract the fields you are interested in.
Once you've written some code to do this if it doesn't work and you are stuck ask a new question showing your code and someone will probably be able to help you further.
HTH
Related
I am working with Coredata. i have an relation with the entity when i fetch my relation it gives the NSSet and i Convert this to NSMutableArray with AllObjects. The issue it gives me __NSSingleObjectArrayI instead of NSMutableArray. Can any one please help me on this. Thanks
Tired Code :-
NSSet *arrPayment = [[[dictPaymentData allValues] valueForKey:#"paymentToInvoice"] valueForKey:#"invoiceToPeople"];
NSMutableArray *arrData = [NSMutableArray arrayWithArray:[arrPayment allObjects]];
This is my __NSSingleObjectArrayI Code :-
<__NSArrayM 0x6000018464f0>(
<__NSSingleObjectArrayI 0x600000a8bdd0>(
{(
<People: 0x600002b44370> (entity: People; id: 0x91782a4d7073f8e8 <x-coredata://0785667E-51C4-4C34-B696-C4374F6315D4/People/p630> ; data: {
archiveStatus = 0;
defaultTerms = 30;
email = nil;
extra1 = nil;
extra2 = nil;
extra3 = nil;
faxNo = nil;
firstName = nil;
from = nil;
fromid = 0;
homeNo = nil;
internalNotes = nil;
lastName = nil;
mobileNO = nil;
modificationDate = "2019-01-17 11:58:50 +0000";
organization = Yogesh;
peopleId = 0;
"sa_City" = nil;
"sa_Country" = nil;
"sa_State" = nil;
"sa_Street1" = nil;
"sa_Street2" = nil;
"sa_Zip" = nil;
selectedCurrency = "en_US";
signature = nil;
sortingString = nil;
status = Cactive;
syncID = nil;
uniqueIdentifier = "6A819F69-DCB0-4B6C-BE60-03151B23541D-3341-0000043F5397E622";
userId = nil;
vatNo = nil;
})
)}
)
)
,
valueForKey: has a special behavior. Applied to an array it returns always an array of all values for the given key.
You are better off using objectForKey:
how to print the key event_id on label.
"all_data" = (
{
"company_logo" = "http://mbdbtechnology.com/projects/officeapp/uploads/event/Voxev\U00e6rket_logo_stort.png";
"event_id" = 8;
"event_name" = "Dit nye kontor i Voxev\U00e6rket";
"event_sort_desc" = "Voxev\U00e6rket tilbyder landsd\U00e6kkende kontorer til ny opstartede";
},
{
"company_logo" = "http://mbdbtechnology.com/projects/officeapp/uploads/event/Image_jpg_2_288X200.jpg";
"event_id" = 7;
"event_name" = "Sunday Special only for women";
"event_sort_desc" = "Declarations of war At midnight on 31 July \U2013 1 Aug, French 2";
},
try this:
NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
//responseData is an NSData object containing the jSON
NSMutableArray *allData = [jsonDict objectForKey:#"all_data"];
for (NSDictionary* dict in allData)
{
NSString *eventID = [dict objectForKey:#"event_id"];
NSLog(#"event ID : %#",eventID);
}
this response i am getting from web service. how to fetch only cities record??
Data = (
{
Cities = (
{
CityCode = 21;
Name = Cork;
Numbers = (
{
Number = 2349990;
PauseOne = 3;
PauseTwo = 3;
}`enter code here`
);
}
)
NSDictionary *cities = myJson[#"Data"][0][#"Cities"][0];
NSLog(#"City Name is = %#", cities[#"Name"]);
NSLog(#"City Code is = %d", [cities[#"CityCode"] intValue]);
This Code is Finally used for you:
NSMutableArray *arrFinalAllCities = [[NSMutableArray alloc]init];
NSMutableArray *arrData = [responseObject objectForKey:#"Data"];
for (int a=0; a<arrData.count; a++)
{
NSMutableArray *arrCity = [[arrData objectAtIndex:a] objectForKey:#"Cities"];
for (int b=0; b<arrCity.count; b++)
{
[arrFinalAllCities addObject:[arrCity objectAtIndex:b]];
}
}
NSLog(#"%#",arrFinalAllCities);
the response u hav posted looks like an nsdictionary. not a server returned json. can u post the exact json returned by server? tip: convert nsdata to nsstring and post dat
I have an array self.seachResult which contains dictionary, I want to add an item to all dictionaries I tried a code like this but I got error, can you provide me by a code that add item 'distance' to it
[[self.seachResult objectAtIndex:0] setObject:#"distance" forKey:#"400"];
this is my array of dictionary:
2013-07-19 02:13:24.929 MyApp[59321:16a03] sorted array of dictionaries: (
{
cid = 2;
image = "http:///images/loginlogo.png";
latitude = "48.245565";
longitude = "16.342333";
manual = "";
movie = "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v";
pcode = 023942435228;
pid = 1;
pname = "example product";
price = "12.00";
qrcode = "";
rid = 1;
rname = "Example Retailer Name";
sale = 0;
"sale_percent" = 0;
"sale_price" = "0.00";
text = "here is text about sample product number 1...\nasdasdasda\nsdfsdfsd\nSdfsdf\nSDfsdfs\ndfsdfsdf\n\n\n";
},
{
cid = 1;
image = "";
latitude = "";
longitude = "";
manual = "";
movie = "";
pcode = 1;
pid = 3;
pname = "test product";
price = "46.00";
qrcode = "";
rid = 2;
rname = "";
sale = 0;
"sale_percent" = 0;
"sale_price" = "35.00";
text = "some text here...
},
{
cid = 2;
image = "http:///testImage.png";
latitude = "48.245565";
longitude = "16.342333";
manual = "";
movie = "";
pcode = 1;
pid = 2;
pname = "sample product 2";
price = "126.00";
qrcode = "";
rid = 1;
rname = "Example Retailer Name";
sale = 1;
"sale_percent" = 20;
"sale_price" = "99.99";
text = "here is text about sample product number 2...\nblah blah blah\nasdasdasd \nASdasdas\nASdasdasd";
}
)
here is the error:
2013-07-19 02:49:54.261 MyApp[59376:16a03] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary setObject:forKey:]: mutating method sent to immutable object'
*** First throw call stack:
(0x3367012 0x2d27e7e 0x3366deb 0x332d347 0x13472 0x1d4d1c7 0x1d4d232 0x1d4d4da 0x1d648e5 0x1d649cb 0x1d64c76 0x1d64d71 0x1d6589b 0x1d65e93 0x1d65a88 0x20c1e63 0x20b3b99 0x1d4ddd2 0x12b9f 0x2d3b705 0x1c6f2c0 0x1c6f258 0x1d30021 0x1d3057f 0x1d2f6e8 0x1c9ecef 0x1c9ef02 0x1c7cd4a 0x1c6e698 0x37a7df9 0x37a7ad0 0x32dcbf5 0x32dc962 0x330dbb6 0x330cf44 0x330ce1b 0x37a67e3 0x37a6668 0x1c6bffc 0x288d 0x27b5)
libc++abi.dylib: terminate called throwing an exception
here is where I create it:
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
self.seachResult =[NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
// [self.productsTableView reloadData];
NSMutableArray *testSorted = [self.seachResult sortedArrayUsingComparator:^NSComparisonResult(NSMutableDictionary *obj1, NSMutableDictionary *obj2) {
NSString *price1 = obj1[#"price"];
NSString *price2 = obj2[#"price"];
NSNumber *n1 = [NSNumber numberWithFloat:[price1 floatValue]];
NSNumber *n2 = [NSNumber numberWithFloat:[price2 floatValue]];
return [n1 compare:n2];
}];
[[self.seachResult objectAtIndex:0] setObject:#"distance" forKey:#"400"];
NSLog(#"sorted array of dictionaries: %#", testSorted);
Your objects created from JSON are all immutable.
self.seachResult =[NSJSONSerialization JSONObjectWithData:responseData options:nil error:nil];
instead of passing nil for options pass NSJSONReadingMutableContainers:
self.seachResult =[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
From the NSJSONSerialization docs:
NSJSONReadingMutableContainers
Specifies that arrays and dictionaries are created as mutable objects.
I have an NSArray built from json data from twitter REST API.
NSArray *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog (#"Element %#", [dict objectAtIndex: 1]);
How to get individual elements from the array, one of the array index item looks like:
Element 1 = {
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Tue Feb 07 11:15:08 +0000 2012";
entities = {
hashtags = (
);
urls = (
);
"user_mentions" = (
);
};
favorited = 0;
geo = "<null>";
id = 166842424398848000;
"id_str" = 166842424398848000;
"in_reply_to_screen_name" = "<null>";
"in_reply_to_status_id" = "<null>";
"in_reply_to_status_id_str" = "<null>";
"in_reply_to_user_id" = "<null>";
"in_reply_to_user_id_str" = "<null>";
place = "<null>";
"retweet_count" = 0;
retweeted = 0;
source = web;
text = "another day is here so ready to be off from work already...";
....
You could try,
NSString *string = [[dict objectAtIndex: 1] objectForKey:#"keyName"];
There's a sub dictionary in your data if I look correctly ("entities")
NSDictionary *entitiesDict = [[dict objectAtIndex: 1] objectForKey:#"entities"];
Use NSDictionary as mentioned :)
Use NSDictionary instead of NSArray and set the values for elements in key. check this link for more idea.
http://www.touch-code-magazine.com/tutorial-fetch-and-parse-json/