There is my XML data:
<item>
<title>The Powerful Academician Able to Reduce Tobacco Hazards</title>
<link>http://china15min.com/2013/03/26/the-powerful-academician-able-to-reduce-tobacco-hazards/</link>
<comments>http://china15min.com/2013/03/26/the-powerful-academician-able-to-reduce-tobacco-hazards/#comments</comments>
<pubDate>Tue, 26 Mar 2013 08:43:37 +0000</pubDate>
<dc:creator>Panda Walking</dc:creator>
<category><![CDATA[Economics]]></category>
<category><![CDATA[Academician of Chinese Engineering Academy]]></category>
<category><![CDATA[China Tobacco Control Association]]></category>
<category><![CDATA[China's tobacco industry]]></category>
<category><![CDATA[CORESTA]]></category>
<category><![CDATA[low-tar cigarettes in China]]></category>
<category><![CDATA[signatory country of the World Health Assembly on Tobacco Control Framework Convention]]></category>
<category><![CDATA[smokers in China]]></category>
<category><![CDATA[Xie Jian Ping]]></category>
<category><![CDATA[Yunnan]]></category>
<guid isPermaLink="false">http://china15min.com/?p=1891</guid>
<description><![CDATA[During the two sessions, the deputies of NPC are obliged to answer journalists’ questions, which may include special topics besides national affairs. For example, why is the “tobacco academician” able to keep his position unswayed despite strong opposition from various... Read More ›<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=china15min.com&blog=37468365&post=1891&subd=china15min&ref=&feed=1" width="1" height="1" />]]></description>
<wfw:commentRss>http://china15min.com/2013/03/26/the-powerful-academician-able-to-reduce-tobacco-hazards/feed/</wfw:commentRss>
<slash:comments>0</slash:comments>
<media:content url="http://1.gravatar.com/avatar/ad06eed181b094ac3022d4507d38c2b7?s=96&d=http%3A%2F%2F1.gravatar.com%2Favatar%2Fad516503a11cd5ca435acc9bb6523536%3Fs%3D96&r=G" medium="image">
<media:title type="html">china15min</media:title>
</media:content>
<media:content url="http://china15min.files.wordpress.com/2013/03/xiejinping.jpg" medium="image">
<media:title type="html">xiejinping</media:title>
</media:content>
</item>
With this method I can get "link" , "title" and "pubDate" node,
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
BQWRSSEntry *entry = [[BQWRSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate];
[entries addObject:entry];
}
}
}
And I use the same method to get the "description", but the result string is null.
How can I get the "description" and the second "media:content url" url string "http://china15min.files.wordpress.com/2013/03/xiejinping.jpg"
Please help me and thank you very much.
I don't know why you can't retrieve the description. You can get the value easily like this:
NSString *description = [item valueForChild:#"description"];
Otherwise to retrieve the second "media:content url" url string follow this:
NSArray *mediaContents = [item elementsForName:#"media:content"];
if ([mediaContents count] > 1)
{
GDataXMLElement *media2 = [mediaContents objectAtIndex:1];
GDataXMLNode *urlString = [media2 attributeForName:#"url"];
}
The complete code should looks like that:
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSString *description = [item valueForChild:#"description"];
NSArray *mediaContents = [item elementsForName:#"media:content"];
if ([mediaContents count] > 1)
{
GDataXMLElement *media2 = [mediaContents objectAtIndex:1];
GDataXMLNode *urlString = [media2 attributeForName:#"url"];
}
BQWRSSEntry *entry = [[BQWRSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate];
[entries addObject:entry];
}
}
}
Related
hello all i am working on a project in which i have to create an array in this format:
{
"1": {
"Child_Gender": "",
"Child_DOB": "",
"Child_tobbacoUse": ""
},
"2": {
"Child_Gender": "",
"Child_DOB": "",
"Child_tobbacoUse": ""
},
but the array i create gives this format
(
{
"Child_DOB" = "";
"Child_Gender" = "";
"Child_tobbacoUse" = "";
},
{
"Child_DOB" = "";
"Child_Gender" = "";
"Child_tobbacoUse" = "";
}
)
i am using the following code:
for (int i = 0; i < arrayChildModel.count; i++)
{
ChildModel *model = [arrayChildModel objectAtIndex:i];
NSString *keyOrder = [NSString stringWithFormat:#"Children_Gender[%d]",i];
NSString *keyQuantity = [NSString stringWithFormat:#"Children_BirthDate[%d]",i];
NSString *keyTobacco = [NSString stringWithFormat:#"Children_HasTobaccoUsage[%d]",i];
//NSString *keyNotes = [NSString stringWithFormat:#"row[%d][description]",i];
childDateOfBirthStr = model.ChildBirthDate ;
childGenderStr = model.ChildGender ;
childTobaccoStr = model.ChildTobaccoUsage;
NSString *string1 = [NSString stringWithFormat:#"%#=%#&",keyOrder,childGenderStr];
NSString *string2 = [NSString stringWithFormat:#"%#=%#",keyQuantity,childDateOfBirthStr];
NSString *string3 = [NSString stringWithFormat:#"%#=%#",keyTobacco,childTobaccoStr];
[stringParams appendString:string1];
[stringParams appendString:string2];
[stringParams appendString:string3];
NSDictionary * ChildDict;
NSArray * ApplicantKeys = [[NSArray alloc]initWithObjects:#"Child_Gender",#"Child_DOB",#"Child_tobbacoUse", nil];
NSArray * ApplicantObjects = [[NSArray alloc]initWithObjects:childGenderStr,childDateOfBirthStr,childTobaccoStr, nil];
ChildDict = [NSDictionary dictionaryWithObjects:ApplicantObjects forKeys:ApplicantKeys];
NSLog(#"Dictionary is %#",ChildDict);
[CompleteArray addObject:ChildDict];
}
NSLog(#"Final Array is %#",CompleteArray);
please help me to convert the output array to the required formatted array
Create one dictionary outer for loop
NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
add this line before NSLog(#"Dictionary is %#",ChildDict);
[dict setObject:ChildDict forKey:[NSString stringWithFormat:#"%ld",i+1]];
[CompleteArray addObject:dict];
Please check following solution it will give you as expected output.
NSMutableDictionary *resultDic = [NSMutableDictionary new];
for (int i = 0; i < arrayChildModel.count; i++)
{
ChildModel *model = [arrayChildModel objectAtIndex:i];
NSString *keyOrder = [NSString stringWithFormat:#"Children_Gender[%d]",i];
NSString *keyQuantity = [NSString stringWithFormat:#"Children_BirthDate[%d]",i];
NSString *keyTobacco = [NSString stringWithFormat:#"Children_HasTobaccoUsage[%d]",i];
//NSString *keyNotes = [NSString stringWithFormat:#"row[%d][description]",i];
childDateOfBirthStr = model.ChildBirthDate ;
childGenderStr = model.ChildGender ;
childTobaccoStr = model.ChildTobaccoUsage;
NSString *string1 = [NSString stringWithFormat:#"%#=%#&",keyOrder,childGenderStr];
NSString *string2 = [NSString stringWithFormat:#"%#=%#",keyQuantity,childDateOfBirthStr];
NSString *string3 = [NSString stringWithFormat:#"%#=%#",keyTobacco,childTobaccoStr];
[stringParams appendString:string1];
[stringParams appendString:string2];
[stringParams appendString:string3];
NSDictionary * ChildDict = [NSDictionary dictionaryWithObjectsAndKeys:childGenderStr,#"Child_Gender",childDateOfBirthStr,#"Child_DOB",childTobaccoStr,#"Child_tobbacoUse", nil];
NSLog(#"Dictionary is %#",ChildDict);
NSString *resultDicKey = [NSString stringWithFormat:#"%d",i+1];
[resultDic setValue:ChildDict forKey:resultDicKey];
}
NSLog(#"Result dic %#",resultDic);
I want to add string value dynamically from result.text and I wanted to display it in this way [#"17052648287",#"17052607335"] without losing the value. How can I do it?
NSMutableArray *strings = [#[#"17052648287",#"17052607335"] mutableCopy];
Add on coding
- (void)captureResult:(ZXCapture *)capture result:(ZXResult *)result{
if (!result) return;
if(self.hasScannedResult == NO)
{
//Scan Result, added into array
NSString *scanPackage = [NSString stringWithFormat:#"%#", result.text];
scanLists = [NSMutableArray new];
[scanLists addObject:scanPackage];
NSUserDefaults *preferences = [NSUserDefaults standardUserDefaults];
NSMutableArray *strings = [[NSMutableArray alloc]init];
strings = [#[result.text] mutableCopy];
[preferences setObject:strings forKey:#"strings"];
NSMutableArray *stringsArray = [preferences objectForKey:#"strings"];
for (NSString *string in stringsArray) {
NSLog(#"string: %#", string);
}
Declare an results array:
NSMutableArray * array = [NSMutableArray new];
Write below code where you get your result.text:
NSString *scanPackage = [NSString stringWithFormat:#"%#", result.text]; // If this code is working for you
[array addObject: scanPackage];
NSString *combined = [array componentsJoinedByString:#","];
NSLog(#"combined: %#", combined);
here is my code. I used NSDictionary and coded to print my json data in my console.but i got error like this:
'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7c971930'
My code:
if(buttonIndex == 0) {
NSLog(#"OK Button is clicked");
}
else if(buttonIndex == 1) {
if([[textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]!=0)
{
if(!self.note)
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newNote = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:context];
NSLog(#"%#",textView.text);
[newNote setValue:textView.text forKey:#"note"];
if([textView.text length]>30)
{
[newNote setValue:[NSString stringWithFormat:#"%#...",[textView.text substringToIndex:25]] forKey:#"title"];
}
else
[newNote setValue:textView.text forKey:#"title"];
[newNote setValue:[NSDate date] forKey:#"mod_time"];
//[newDevice setValue:self.versionTextField.text forKey:#"version"];
//[newDevice setValue:self.companyTextField.text forKey:#"company"];
How to overcome this problem to work and to print my data in my console
Help me out. I am struggling for 2 hours.I googled and change all change.But cant get data in my console. Thanks in advance
I guess you can get data like below this
NSDictionary *monday = jsonResults[#"original"];
NSArray * arrFile = monday[#"files"];
for (NSDictionary *theCourse in arrFile)
{
....
}
Did you checked that received data (i.e., returnData) from sendSynchronousRequest: is returning a plain data?
If the data received is in Base64, you might have to decode this NSData to plain data, and then go ahead with String conversion.
NSData *decodedData = [[NSData alloc] initWithBase64EncodedData:responseData options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *str = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
// convert Json to NSDictionary
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
// NSLog(#"%#",jsonResults);
int count = [[jsonResults valueForKey:#"count"] intValue];
NSArray *arrayData = [jsonResults copy];
NSMutableArray *arrayPDFName = [[NSMutableArray alloc]init];
for(int i = 0;i < [arrayData count];i++)
{
NSDictionary *dictOriginal = [[arrayData objectAtIndex:2]valueForKey:#"original"];
int countOriginal = [[dictOriginal valueForKey:#"count"] intValue];
NSLog(#"The countOriginal is - %d",countOriginal);
NSArray *arrayFiles = [[dictOriginal valueForKey:#"files"] copy];
NSLog(#"The arrayFiles are - %#",arrayFiles);
for(int j=0;j<[arrayFiles count];j++)
{
NSString *strCreatedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"created_time"]];
NSString *strLastModifiedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"last_modified_time"]];
NSString *strID = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"id"]];
NSString *strName = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"name"]];
NSLog(#"The created_time is - %#",strCreatedTime);
NSLog(#"The last_modified_time is - %#",strLastModifiedTime);
NSLog(#"The is is - %#",strID);
NSLog(#"The name is - %#",strName);
[arrayPDFName addObject:strName];
}
}
Currently working on a way to create a new NSMutableDictionary from my returned JSON data. I want to extract: tide.tideSummary.data.type and tide.tideSummary.date.epoch - I want to create a new array of dictionaries but with these 2 keys.
Below is what I have now:
for (NSDictionary *dict in self.tideSummary) {
NSString *type = [self.tideSummary valueForKeyPath:#"data.type"];
NSString *date = [self.tideSummary valueForKeyPath:#"date.epoch"];
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
}
Right now my NSLog returns perfectly for each key. Sample log as of now, what is incorrect
epoch = (
1388724761,
1388746063,
...
My goal it to make this output: - an array of dictionaries.
{
type: Sunrise,
epoch: 1336116677
},
{
type: Sunset,
epoch: 1336116677
},
{
type: Moonset,
epoch: 1336116677
},
...
I think I am pretty close, I just need to join those 2 key value pairs in their own object. Do I need to create a NSMutableArray and addObject to the previously created dictionary?
Data I am working with:
"tideSummary": [
{
"date": {
"pretty": "11:58 AM PST on December 19, 2013",
...
"epoch": "1387483136"
},
"utcdate": {
"pretty": "7:58 PM GMT on December 19, 2013",
...
"epoch": "1387483136"
},
"data": {
"height": "5.97 ft",
"type": "High Tide"
}
},
Thoughts on how to make this happen?
You are very close to your output but the shown output is not fully Dictionary it is an array of Dictionaries, so you need to do something like this.
NSMutableArray *finalOutput = [[NSMutableArray alloc] init]; //Add this
for (NSDictionary *dict in self.tideSummary)
{
NSMutableDictionary *sunCycleDictionary = [[NSMutableDictionary alloc] init]; //Add this
NSString *type = [self.tideSummary valueForKeyPath:#"data.type"];
NSString *date = [self.tideSummary valueForKeyPath:#"date.epoch"];
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
[finalOutput addObject: sunCycleDictionary]; //Add this
}
NSLog(#"out of loop: %#", finalOutput);
Try this
NSMutableArray *outputArray = [[NSMutableArray alloc] init];
for (NSDictionary *dict in self.tideSummary)
{
NSMutableDictionary *sunCycleDictionary = [[NSMutableDictionary alloc] init];
NSString *type = [dict valueForKeyPath:#"data.type"];
NSString *date = [dict valueForKeyPath:#"date.epoch"];
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
[outputArray addObject:sunCycleDictionary];
}
NSLog(#"output array : %#", outputArray);
Try This
NSMutableArray *temp =[[NSMutableArray alloc]init];
for (NSDictionary *dict in self.tideSummary) {
NSString *type = [self.tideSummary valueForKeyPath:#"data.type"];
NSString *date = [self.tideSummary valueForKeyPath:#"date.epoch"];
NSLog(#"type: %#", type);
[sunCycleDictionary setValue:(type) forKey:#"type"];
[sunCycleDictionary setValue:(date) forKey:#"epoch"];
[temp addObject: sunCycleDictionary];
NSLog(#"in loop: %#", temp);
}
int i=0;
while (i<[_arayResjoBID count]) {
NSLog(#"%d",i);
NSDictionary *dict=[[NSMutableDictionary alloc]init];
[dict setValue:[[_arayResjoBID objectAtIndex:i]valueForKeyPath:#"BarCode"] forKey:#"barcode"];
[dict setValue:[[_arayResjoBID objectAtIndex:i] valueForKeyPath:#"ItemName"] forKey:#"itemname"];
[dict setValue:[[_arayResjoBID objectAtIndex:i] valueForKeyPath:#"Quantity"] forKey:#"quantity"];
[dict setValue:#"NO" forKey:#"Yes"];
[_arayFilter insertObject:dict atIndex:i];
i++;
}
}
NSLog(#"%#",_arayFilter);
[self.tableView reloadData];
OUTPUT: in debug area
(
{
Yes = NO;
barcode = 1002690094467;
itemname = "Box Oversized 100X80x80";
quantity = 5;
},
{
Yes = NO;
barcode = 1002690094474;
itemname = "Road Case Large";
quantity = 2;
},
{
Yes = NO;
barcode = 1002690094481;
itemname = "Road Case New Double";
quantity = 4;
}
)
I have a NSDictionary looks like this:
data = {
start = {
name = "abc";
age = "123";
id = AA838DDE;
};
};
how can I parser the dictionary to get individual name, age, and id? Thanks.
NSString *name = dictionary[#"data"][#"start"][#"name"];
I add an other answer because I hate the new Objective-C syntax (sorry #Raphael Olivieira)
NSString *name = [[[[dictionary objectForKey:#"data"] objectForKey:#"start"] objectAtIndex:0] objectForKey:#"name"];
NSLog(#"%#", name);
Longer than the previous answer but you know what you do and you don't code in C.
BTW, using the other syntax :
NSString *name = dictionary[#"data"][#"start"][0][#"name"];
NSLog(#"%#", name);
why don't you simply try:
int arrCount = [[[dictionaryObject valueForKey:#"data"] objectForKey:#"start"] count];
for(int i = 0 ; i < arrCount ; i++)
{
NSString *strName = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"name"];
NSString *strAge = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"age"];
NSString *strID = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"id"];
NSLog(#"%# - %# - %#", strName, strAge, strID);
}