Skip to content

Instantly share code, notes, and snippets.

@joshbirk
Created October 19, 2011 03:08
Show Gist options
  • Save joshbirk/1297393 to your computer and use it in GitHub Desktop.
Save joshbirk/1297393 to your computer and use it in GitHub Desktop.
Apex Example of the new JSON parser/serialization
public with sharing class ApexJSONExample {
public ApexJSONExample() {
}
public void testSerialize() {
Flog__c f = new Flog__c();
Dog__c dog = [SELECT ID, Name, Breed__c from Dog__c LIMIT 1];
f.JSON__c = JSON.serialize(dog);
insert f;
//SELECT ID, Name, JSON__c from Flog__c
}
public void testDeserialize(string newName) {
Flog__c f = [SELECT ID, Name, JSON__c from Flog__c LIMIT 1];
Dog__c dog = (Dog__c)JSON.deserialize(f.JSON__c,Dog__c.class);
dog.Name = newName;
update dog;
//SELECT Id, Name from Dog__c WHERE Name = 'NewDogName'
}
public List<String> getFlickrImages() {
HttpRequest req = new HttpRequest();
req.setEndpoint('http://api.flickr.com/services/feeds/photos_public.gne?format=json');
req.setMethod('GET');
Http http = new Http();
HTTPResponse res = http.send(req);
String feed = res.getBody();
feed = feed.replace('jsonFlickrFeed(','');
feed = feed.replace('})','}');
List<String> urls = new List<String>();
JSONParser parser = JSON.createParser(feed);
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'm')) {
parser.nextToken();
urls.add(parser.getText());
}
}
return urls;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment