Newswire API

Here is the code 🙂

import org.json.*;

String typeOfData = “json”;
String baseURL = “http://api.nytimes.com/svc/news/v3/content/NYT/Arts/.” + typeOfData + “?&limit=20”;
String apiKey = “#######”;
String headline;
String publishedDate;

void setup() {
size(300,300);

//—————————————————————————————————
//Getting the Data
//Create the URL to request
//String request = baseURL + “&title=” + headline + “&published_date=” + publishedDate + “&api-key=” + apiKey;
String request = baseURL + “&api-key=” + apiKey;

if(typeOfData.equals(“xml”)) {
XMLElement xml = new XMLElement(this, request);
println(xml.getChildCount());

XMLElement results = xml.getChild(“results”);
int nResults = results.getChildCount();

for(int i=0; i<nResults; i++) {
XMLElement thisArticle = results.getChild(i);
String title = thisArticle.getChild(“abstract”).getContent();
println(title);

XMLElement des_facet = thisArticle.getChild(“des_facet”);
int nFacets = des_facet.getChildCount();

for(int j=0; j<nFacets; j++) {
String thisFacet = des_facet.getChild(j).getContent();
println(thisFacet);
}

println();
}
} else {

//—————————————————————————————————
//JSON Stuff
//We try to get the data, if not we do the catch statement

//Get JSON from Server,”loadStrings() gets data, join adds “” to make sure it is a string
String result = join( loadStrings( request ), “”);

try {
//Convert Result string into JSON Object
JSONObject nytData = new JSONObject(result);

//Print the total results available
println(nytData.getString(“num_results”));

//Get results as an array
JSONArray results = nytData.getJSONArray(“results”);

//Results array has each article as a JSON Object, loop through and get each article
for(int i=0; i<results.length(); i++) {
//Create variable to reference this JSON object in array, setting type to JSON Object so compiler doesn’t freak out
JSONObject thisArticle = (JSONObject)results.get(i);

//Print Title
String title = thisArticle.getString(“title”);
println(title);

//thisArticle is JSON Object, to loop through des_facet we get it as an array of JSON Objects from thisArticle
//Use Try…Catch because not every article has des_facet
try {
//Get array
JSONArray desFacet = thisArticle.getJSONArray(“des_facet”);

//Loop through
for(int j=0; j<desFacet.length(); j++) {
//Print each item
println(desFacet.getString(j));
}
} catch (JSONException e) {
println(“No Des Facet for this article!”);
}

//Separate articles with blank line
println();
}
}
catch (JSONException e) {
println (“There was an error parsing the JSONObject.”);
};
}

/*
//Format Examples

//XML Format

 

 

 

 

 

 

 

 

 

 

 

 

//JSON Format
{
articles: {
article: {
title,
body,
etc
},
article,
article
}
}

*/
}

This entry was posted in Homework. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *