Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
StackExchange API on Salesforce!
public class StackExchangeService{
public List<SFSEQuestion> getStackExchangeQuestionsDeserialize(){
Http httpQuestions = new Http();
HttpRequest requestQuestions = new HttpRequest();
requestQuestions.setEndpoint('http://api.stackexchange.com/2.2/users/605/questions?order=desc&sort=activity&site=salesforce');
requestQuestions.setMethod('GET');
requestQuestions.setHeader('Content-Type', 'application/json');
HTTPResponse responseQuestions = httpQuestions.send(requestQuestions);
List<SFSEQuestion> questions = new List<SFSEQuestion>();
SFSEQuestions jsonQuestions = (SFSEQuestions)JSON.deserialize(responseQuestions.getBody(), SFSEQuestions.class);
questions = jsonQuestions.getItems();
return questions;
}
public List<SFSEQuestion> getStackExchangeQuestionsParsing(){
Http httpQuestions = new Http();
HttpRequest requestQuestions = new HttpRequest();
requestQuestions.setEndpoint('http://api.stackexchange.com/2.2/users/605/questions?order=desc&sort=activity&site=salesforce');
requestQuestions.setMethod('GET');
requestQuestions.setHeader('Content-Type', 'application/json');
HTTPResponse responseQuestions = httpQuestions.send(requestQuestions);
List<SFSEQuestion> questions = new List<SFSEQuestion>();
JSONParser parser = JSON.createParser(responseQuestions.getBody());
SFSEQuestion question = new SFSEQuestion();
while (parser.nextToken() != null) {
if((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'score')) {
parser.nextToken();
question.setVotes(parser.getIntegerValue());
}
if((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'link')) {
parser.nextToken();
question.setLink(parser.getText());
}
if((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'title')) {
parser.nextToken();
question.setTitle(parser.getText());
}
if(question.isComplete()){
questions.add(question);
question = new SFSEQuestion();
}
}
return questions;
}
public class SFSEQuestions{
public List<SFSEQuestion> items;
public SFSEQuestions(){
}
public List<SFSEQuestion> getItems(){
return items;
}
public void setItems(List<SFSEQuestion> items){
this.items = items;
}
}
public class SFSEQuestion{
public String title;
public String link;
public Integer votes;
public SFSEQuestion(){
}
public Boolean isComplete(){
return title != null && link != null && votes != null;
}
public String getTitle(){
return title;
}
public void setTitle(String title){
this.title = title;
}
public String getLink(){
return link;
}
public void setLink(String link){
this.link = link;
}
public Integer getVotes(){
return votes;
}
public void setVotes(Integer votes){
this.votes = votes;
}
}
}
Owner

jessealtman commented Apr 19, 2014

This code is from my blog article StackExchange API on Salesforce!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment