I want to get tweets with a specific hashtag. I use the Twitter search URL. This is my code:
NSMutableString *urlString = [NSMutableString stringWithFormat:#"%s","http://search.twitter.com/search.json?q=%23zesdaagsegent"];
NSURL *url = [NSURL URLWithString:urlString];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(#"%#", data);
NSError *error;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"%#", json);
NSMutableArray *results =[NSMutableArray array];
for(NSDictionary *item in json)
{
[results addObject:[item objectForKey:#"results"]];
}
My NSLog gets me the output I need:
2013-05-28 09:48:45.080 ZesdaagseGent[572:11303] {
"completed_in" = "0.023";
"max_id" = 339031661368975360;
"max_id_str" = 339031661368975360;
page = 1;
query = "%23zesdaagsegent";
"refresh_url" = "?since_id=339031661368975360&q=%23zesdaagsegent";
results = (
{
"created_at" = "Mon, 27 May 2013 14:53:41 +0000";
"from_user" = SigfridMaenhout;
"from_user_id" = 369194526;
"from_user_id_str" = 369194526;
"from_user_name" = "Sigfrid Maenhout";
geo = "";
id = 339031661368975360;
"id_str" = 339031661368975360;
"iso_language_code" = nl;
metadata = {
"result_type" = recent;
};
source = "<a href="http://twitter.com/">web</a>";
text = "#zesdaagsegent Het is een zonnige dag hier in Merelbeke. We verlangen allemaal naar een beetje zonnestralen in het
gezicht, toch?";
}
);
"results_per_page" = 15;
"since_id" = 0;
"since_id_str" = 0; }
I need the array "results" with the objects in. My problem is that I can't get the results in an NSMutableArray with the method objectForKey.
Does anyone has an idea?
Try this :
NSMutableArray *results = [NSMutableArray array];
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
for (NSDictionary *result in jsonResponse[#"results"]) {
[results addObject:result];
}
And you should have a NSArray results containing X NSDictionary for each of the matching tweets.
PS : [#"results"] is the modern Objective-C syntax for [NSDictionary objectForKey:#"results"]
Related
Im having hard time while trying to parse the following json array. How to parse it. The other answers in web doesn't seem to solve my problem.
{
"status": 1,
"value": {
"details": [
{
"shipment_ref_no": "32",
"point_of_contact": {
"empid": ""
},
"products": {
"0": " Pizza"
},"status": "2"
},
{
"shipment_ref_no": "VAPL/EXP/46/14-15",
"point_of_contact": {
"empid": "60162000009888"
},
"products": {
"0": "MAIZE/CORN STARCH"
},
"status": "5"
}
]
}
}
I have to access the values of each of those keys.
Following is my code
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
This is how you can parse your whole dictionary:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSArray *details = [[dataDictionary objectForKey:#"value"] objectForKey:#"details"];
for (NSDictionary *dic in details) {
NSString *shipmentRefNo = dic[#"shipment_ref_no"];
NSDictionary *pointOfContact = dic[#"point_of_contact"];
NSString *empId = pointOfContact[#"empid"];
NSDictionary *products = dic[#"products"];
NSString *zero = products[#"0"];
NSString *status = dic[#"status"];
}
NSString *pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSArray *argsArray = [[NSArray alloc] initWithArray:[jsonDic objectForKey:#"details"]];
//argsArray holds objects in form of NSDictionary.
for(NSDictionary *response in argsArray) {
//String object
NSLog(#"%#", [response valueForKey:#"shipment_ref_no"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"point_of_contact"] valueForKey:#"empid"]);
//String object
NSLog(#"%#", [response valueForKey:#"status"]);
//Dictionary object
NSLog(#"%#", [[response objectForKey:#"products"] valueForKey:#"0"]);
}
I believe you should surely ask your server developer to update the response format.
Also, you can always use Model classes to parse your data. Please check this, How to convert NSDictionary to custom object.
And yes, I'm using this site to check my json response.
EDIT: Following answer is in javascript!
You can parse your json data with:
var array = JSON.parse(data);
and then you can get everything like this:
var refno = array["value"]["details"][0]["shipment_ref_no"];
you can parse like ...
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *dictValue = [[NSDictionary alloc] initWithDictionary:[jsonDic objectForKey:#"value"]];
NSArray *arrDetails = [[NSArray alloc] initWithArray:[dictValue objectForKey:#"details"]];
for (int i=0; i<arrDetails.count; i++)
{
NSDictionary *dictDetails=[arrDetails objectAtIndex:i];
NSDictionary *dictContact = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"point_of_contact"]];
NSDictionary *dictProduct = [[NSDictionary alloc] initWithDictionary:[dictDetails objectForKey:#"products"]];
}
NSDictionary *response = //Your json
NSArray *details = response[#"value"][#"details"]
etc. Pretty easy
Update your code as follows. You are trying to read the details array from the top level whereas in your data its inside the value key. So you should read the value dict and within that read the details array.
NSString* pendingResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSData *jsonData = [pendingResponse dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
NSDictionary *valueDict = [jsonDic objectForKey:#"value"];
NSArray *argsArray = [[NSArray alloc] initWithArray:[valueDict objectForKey:#"details"]];
NSDictionary *argsDict = [[NSDictionary alloc] initWithDictionary:[argsArray objectAtIndex:0]];
NSLog(#"keys = %#", jsonDic[#"values"]);
I think your problem is that you have:
NSLog(#"keys = %#", jsonDic[#"values"]);
But it should be:
NSLog(#"keys = %#", jsonDic[#"value"]);
Below is code for parsing JSON array. i have used to parse JSON array from file but you can also do this using response link also.I have provided code for both and are below.
// using file
NSString *str = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"json"];
NSData *data = [[NSData alloc]initWithContentsOfFile:str];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
// using url
NSURL *url = [NSURL URLWithString:#"www.xyz.com"]; // your url
NSData *data = [[NSData alloc]initWithContentsOfURL:url];
NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSMutableDictionary *dictValues = [[NSMutableDictionary alloc]initWithDictionary:[dict valueForKey:#"value"]];
NSMutableArray *array = [[NSMutableArray alloc]initWithArray:[dictValues valueForKey:#"details"] copyItems:YES];
NSLog(#"Array Details :- %#",array);
IOS newb here having trouble with debugging.
Am trying to handle a json feed but code below is breaking at
- (void)viewDidLoad {
[super viewDidLoad];
shnote = #"shnote”;
lnote = #"lnote”;
myObject = [[NSMutableArray alloc] init];
self.title=#"Challenges";
NSData *jsonSource = [NSData dataWithContentsOfURL:
[NSURL URLWithString:#"http://www.~~/webservice.php"]];
id jsonObjects = [NSJSONSerialization JSONObjectWithData:
jsonSource options:NSJSONReadingMutableContainers error:nil];
for (NSDictionary *dataDict in jsonObjects) {
//BREAKS HERE
NSString *shnote_data = [dataDict objectForKey:#"shnote”];
//ABOVE LINE HIGHLIGHTED IN GREEN AT BREAKPOINT
NSString *lnote_data = [dataDict objectForKey:#"lnote”];
dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
shnote_data, shnote,lnote_data, lnote,nil];
[myObject addObject:dictionary];
}
/*
*/
}
The line highlighted in console is
dataDict = (NSDictionary *const)#"notes"
notes is name of table but other than that I am clueless.
Would appreciate any suggestions.
Your data source is of the format:
{
"notes": [
{
"row": {
"shnote": <...>,
"lnote": <...>
}
},
{
"row": {
"shnote": <...>,
"lnote": <...>
}
},
<...>
]
}
Steps to fetch each row content should therefore be:
Read value of notes property
Iterate through each row
Read value of row property
Read shnote and lnote properties
You're missing steps 1, 2 and 3. In code:
NSURL *url = [NSURL URLWithString:#"http://www.~~/webservice.php"];
NSData *jsonSource = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonSource options:NSJSONReadingMutableContainers error:nil];
NSDictionary *notes = jsonObject[#"notes"];
for(NSDictionary *note in notes) {
NSDictionary *row = note[#"row"];
NSString *shnote = row[#"shnote"];
NSString *lnote = row[#"lnote"];
NSLog(#"%#, %#", shnote, lnote);
}
Here's an example of my data:
[
{
code: "DRK",
exchange: "BTC",
last_price: "0.01790000",
yesterday_price: "0.01625007",
top_bid: "0.01790000",
top_ask: "0.01833999"
}
]
I'm trying to retrieve the value for last_price by loading the contents of my NSDictionary into an Array.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
self.darkPosts = [NSMutableArray array];
NSArray *darkPostArray = [darkDict objectForKey:#""];
for (NSDictionary *darkDict in darkPostArray) {...
But my json doesn't have a root element, so what do I do?
Additionally, when using the suggested answer, the output is ("...
- (void)viewDidLoad{
[super viewDidLoad];
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSDictionary *darkDict = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSString *lastP = [darkDict valueForKey:#"last_price"];
self.dark_label.text = [NSString stringWithFormat: #"%#", lastP];
}
It looks like you are wanting to iterate over your results. The root element is an array not a dictionary so you can just start iterating
NSError *error = nil;
NSArray *items = [NSJSONSerialization JSONObjectWithData:darkData
options:kNilOptions
error:&error];
if (!items) {
NSLog(#"JSONSerialization error %#", error.localizedDescription);
}
for (NSDictionary *item in items) {
NSLog(#"last_price => %#", item[#"last_price"]);
}
If you literally just want to collect an array of the last_price's then you can so this
NSArray *lastPrices = [items valueForKey:#"last_price"];
Convert the JSON to an NSArray with NSJSONSerialization. Then access the value:
NSData *darkData = [#"[{\"code\":\"DRK\",\"exchange\": \"BTC\",\"last_price\": \"0.01790000\",\"yesterday_price\": \"0.01625007\",\"top_bid\": \"0.01790000\"}, {\"top_ask\": \"0.01833999\"}]" dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:darkData
options:0
error:&error];
NSString *value = array[0][#"last_price"];
NSLog(#"value: %#", value);
NSLog output:
value: 0.01790000
If you are having trouble post the code you have written to get some help.
-- updated for new OP code:
The web service returns a JSON array or dictionaries not a JSON dictionary. First you have to index into the array and then index into the dictionary.
NSURL *darkURL = [NSURL URLWithString:#"https://api.mintpal.com/v1/market/stats/DRK/BTC"];
NSData *darkData = [NSData dataWithContentsOfURL:darkURL];
NSError *error = nil;
NSArray *darkArray = [NSJSONSerialization JSONObjectWithData:darkData options:0 error:&error];
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
NSLog(#"lastP: %#", lastP);
NSLog output:
lastP: 0.01970000
Note that the two lines:
NSDictionary *darkDict = darkArray[0];
NSString *lastP = [darkDict valueForKey:#"last_price"];
can be replaced with the single line using array indexing:
NSString *lastP = darkArray[0][#"last_price"];
Where the "[0]" gets the first array element which is a NSDictionary and the "[#"last_price"]" gets the names item from the dictionary.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
hi i getting json from an external source and parsing it in ios. my code is below
Note = json and cats variables are NSArray;
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
cats = [[NSMutableArray alloc] init];
for (int i=0; i < json.count; i++) {
NSString * CatId = [[json objectAtIndex:i] objectForKey:#"id"];
NSString * CatName = [[json objectAtIndex:i] objectForKey:#"name"];
NSString * CatIcon = [[json objectAtIndex:i] objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
and json is here
{"categories":[{"id":1,"name":"Healthcare","icon":"/icons/images/65/original_56.png?1386745569"},{"id":10,"name":"Mall","icon":"/icons/images/60/original_51.png?1386745369"},{"id":11,"name":"Taupheq","icon":"/icons/images/23/original_14.png?1386744595"},{"id":12,"name":"Hotel","icon":"/icons/images/27/original_18.png?1386744659"},{"id":13,"name":"SPA","icon":"/icons/images/48/original_39.png?1386745093"},{"id":14,"name":"ATM","icon":"/icons/images/22/original_13.png?1386744578"},{"id":15,"name":"Travel","icon":"/icons/images/12/original_3.png?1386744393"},{"id":16,"name":"Game zone","icon":"/icons/images/68/original_59.png?1386745626"},{"id":17,"name":"Academic","icon":"/icons/images/10/original_1.png?1386744264"},{"id":18,"name":"Textile","icon":"/icons/images/46/original_37.png?1386745050"}]}
Try this:
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *catsArray = [NSArray arrayWithArray:[json objectForKey:#"categories"]];
cats = [[NSMutableArray alloc] init];
for (int i = 0; i < catsArray.count; i++) {
NSString * CatId = [[catsArray objectAtIndex:i] objectForKey:#"id"];
NSString * CatName = [[catsArray objectAtIndex:i] objectForKey:#"name"];
NSString * CatIcon = [[catsArray objectAtIndex:i] objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
}
try this:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
json = [dict objectForKey:#"categories"];
When you are trying this:
NSString * CatId = [[json objectAtIndex:i] objectForKey:#"id"];
It translates into: Array -> Dictionary -> String
But you can see you dont want this.
You want: Dictionary -> Array -> Dictionary ->String
In Code:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *array = [dict objectForKey:#"categories"];
NSString * CatId = [[array objectAtIndex:0] objectForKey:#"id"];
try this . . .
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray * cat = [json objectForKey:#"categories"];
for(NSDictionary * tempdict in cat)
{
NSString * CatId = [NSString stringWithFormat:#"%#",[tempdict objectForKey:#"id"]];
NSString * CatName = [tempdict objectForKey:#"name"];
NSString * CatIcon = [tempdict objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
}
THis should work : Consider the Json as NSMutableArray and then easily you ail get the array of the object one by one :
NSMutableArray *userDetails = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:nil];
NSLog(#"User Det %#", userDetails);
if (userDetails == nil || [userDetails count] == 0) {
} else {
// 3. iterate the array; each element is a dictionary...
for (NSDictionary *lesson in userDetails)
{
NSString * CatId = [[catsArray objectAtIndex:i] objectForKey:#"id"];
NSString * CatName = [[catsArray objectAtIndex:i] objectForKey:#"name"];
NSString * CatIcon = [[catsArray objectAtIndex:i] objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
}
}
NSURL * url = [NSURL URLWithString:#"http://myurl.json"];
NSData * data = [NSData dataWithContentsOfURL:url];
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *myArray = [jsonData objectForKey:#"categories"];
cats = [[NSMutableArray alloc] init];
for (NSDictionary *temp in myArray) {
NSString * CatId = [NSString stringWithFormat:#"%d",[temp objectForKey:#"id"]];
NSString * CatName = [temp objectForKey:#"name"];
NSString * CatIcon = [temp objectForKey:#"icon"];
categories * cat = [[categories alloc] initWithCId:CatId andCName:CatName andCIcon:CatIcon];
[cats addObject:cat];
}
I'm having some trouble getting to the data I want to in the JSON file. Here is a shortened version of the output from my console:
{
AUD = {
15m = "125.15547";
24h = "124.74";
buy = "121.0177";
last = "125.15547";
sell = "123.44883";
symbol = "$";
};
BRL = {
15m = "120.34";
24h = "120.34";
buy = "120.34";
last = "120.34";
sell = "120.34";
symbol = "R$";
};
CAD = {
15m = "129.08612";
24h = "131.07";
buy = "128.66227";
last = "129.08612";
sell = "129.08612";
symbol = "$";
};
}
I'm trying to parse the file using the built in JSON parsing library. Here is the parser in my viewDidLoad method:
_tickerArray = [NSMutableArray array];
NSURL *tickerDataURL = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSData *jsonData = [NSData dataWithContentsOfURL:tickerDataURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
NSArray *ar = [NSArray arrayWithObject:dataDictionary];
for (NSString *key in [dataDictionary allKeys]) {
for (NSDictionary *dict in ar) {
TickerData *t;
t.currency = [dict objectForKey:key];
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
I want to store the currency code (like AUD or BRL) into t.currency along with some of the other data contained in the currency dictionary but now my app is crashing.
Error code:
NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil
None of the objects seem to get added to the _tickerArray
Help?
EDIT: Getting the keys to display with the proper data populating other fields:
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];
TickerData *t=[[TickerData alloc] init];
t.currency = key;//EDITED
t.symbol = [dic objectForKey:#"symbol"];
t.last = [dic objectForKey:#"last"];
[_tickerArray addObject:t];
}
t is nil, you have to alloc/ init it:
TickerData *t = [[TickerData alloc] init];
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#", dataDictionary);
//NSArray *ar = [NSArray arrayWithObject:dataDictionary];//REMOVED
for (NSString *key in [dataDictionary allKeys]) {
NSDictionary *dic=[dataDictionary objectForKey:key];//ADDED
for (NSString *dickey in [dic allKeys]) { //MODIFIED
NSDictionary *dict=[dic objectForKey:dicKey];//ADDED
TickerData *t=[[TickerData alloc] init];//ALLOC INIT ?
t.currency = key;//EDITED
t.symbol = [dict objectForKey:#"symbol"];
t.last = [dict objectForKey:#"last"];
[_tickerArray addObject:t];
}
}
Your data doesn't contain any array, its all dictionaries, try the above code see comments too..
Hope it works..
Edited:
Yes you have initialize the object too, as suggested above in other answers..
Try it....
NSURL *url = [NSURL URLWithString:#"https://blockchain.info/ticker"];
NSLog(#"API : %#",url);
NSMutableData *jsonData = [NSMutableData dataWithContentsOfURL:url];
NSString *data = [[NSString alloc] initWithBytes: [jsonData mutableBytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
dictionary = [data JSONValue];
NSDictionary *dict = [dictionary objectForKey:#"AUD"];
NSLog(#"%#",dict);
NSString *last = [dict valueForKey:#"last"];
NSLog(#"%#",last);