Jackson polymorphic serialization with Autovalue

One of the most powerful features in the Java JSON library Jackson, is support for polymorphic serialization. That is, when deserializaing a JSON (or XML) blob to a supertype, with proper configuration, an object of the correct subtype will be instantiated. Likewise, type information will be included in serialization.

This allows for Java clients and servers to communicate using JSON and use a common interface to share types.

// Animal.java
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonTypeInfo(
  use=JsonTypeInfo.Id.NAME, 
  include=JsonTypeInfo.As.PROPERTY, 
  property="type")
@JsonSubTypes({
  @JsonSubTypes.Type(name="cat", value=Cat.class),
  @JsonSubTypes.Type(name="dog", value=Dog.class)
})
public interface Animal {
  String vocalize();
}

// Dog.java
public class Dog implements Animal {
  @Override String vocalize() {
    return "bark";
  }
}

//Cat.java
public class Cat implements Animal {
  @Override String vocalize() {
    return "meow";
  }
}

//Example.java
import com.fasterxml.jackson.databind.ObjectMapper;

public class Example {
  private static final ObjectMapper MAPPER = new ObjectMapper();

  public static main() {
    Animal jsonAnimal
        = MAPPER.readValue("{type=\"dog\"}", Animal.class);
    jsonAnimal.vocalize(); // "bark"

    Animal cat = new Cat();
    MAPPER.writeValueAsString(cat); // "{type=\"cat\"}"
  }
}

Typically this can be achieved using the JsonTypeInfo and JsonSubTypes annotation above. The JsonTypeInfo annotation allows for considerable flexibility in how the type information is included in the serialized object.

However, I did find one situation where using the @JsonSubTypes annotation directly on the interface is insufficient. This is when using <>AutoValue.

@AutoValue
abstract public class Horse implements Animal {
  @Override String vocalize() {
    return "nay";
  }

  static Animal create() {
      return new AutoValue_Horse();
  }
}

Adding @JsonSubTypes.Type(name="horse", value=Horse.class) to Animal will not provide the symmetric serialization we may expect here. Instead we’ll find the value for type in our JSON markup will be the generated type AutoValue_Horse and as a result we will not be able to deserialize the JSON blob to an `Animal` as that type isn’t known to the `Animal` interface.

The workaround here is adding additional type information to Horse.

@AutoValue
@JsonTypeName(Horse.JSON_TYPE_NAME)
abstract public class Horse implements Animal {
  static final String JSON_TYPE_NAME = "horse";
  ...
}

@JsonTypeInfo(
  use=JsonTypeInfo.Id.NAME, 
  include=JsonTypeInfo.As.PROPERTY, 
  property="type")
@JsonSubTypes({
  @JsonSubTypes.Type(name="cat", value=Cat.class),
  @JsonSubTypes.Type(name="dog", value=Dog.class),
  @JsonSubTypes.Type(name=Horse.JSON_TYPE_NAME, value=Horse.class)
})
public interface Animal {
  String vocalize();
}

While it requires an additional annotation, adding JsonTypeName to Horse ensures that even the generated type AutoValue_Horse will include the correct type name in the JSON markup so polymorphic serialization behaves as intended!

Ruby Summer Conference Extravaganza

As this summer wraps up, I’d like to thanks Arlington Ruby for their Unconference and Steel City Ruby Conf for putting together great events.

The events were both accessible and affordable, the latter being unfortunately uncommon for many conferences. Also, while both events offered tracks that appealed to intermediate and expert Rubyists, they also offered content that very much met the goal of getting more people involved with the language and programming in general. Finally, the group of attendees and companies represented at both events made for a great time!

Some (Slightly Related) Ruby Links

CommanLineFu – A great resource for command line tricks and wizardry.  Their twitter feed that only tweets content over the 100 vote threshold is particularly useful for identifying the best of the best.  Of course if we are going to dive into command line tricks this XKCD is relevant.

RubyMotion – iOS development with Ruby.

Wild Nothing – Gemini

It isn’t often in life that you get second chances. Whether it’s with a cute girl whose number you don’t ask for or a band whose name you don’t remember to write down, rarely do you get a second pass. Wild Nothing is a band that I was lucky enough to have re-enter my orbit and as they will shortly be debuting their sophomore LP the timing seems appropriate to have them make an appearance as my song of the week.

I first was introduced to Jack Tatum and his band Facepaint on a trip to my beloved college town of Blacksburg, VA in October 2009. Something about the ethereal sound, a perfect crowd size, and a couple PBRs struck me that night. I instructed my friends at Gillie’s that I needed to remember this band so I could check them out online later. Well, as with many things worth remembering, and even more that occur adjacent to Hokie football, I lost their name with that weekend.

A couple years later while listening through Hype Machine’s Best Albums of 2010 on Hype Machine I found myself drawn to #44, Wild Nothing’s Gemini. After taking pass after pass through the album, I started digging into the band’s Wikipedia page. The pieces quickly came together at that point, that band I saw playing for 60 people in Blacksburg had started receiving national attention.

I picked the title track off of their 2010 release as the song of the week over their new single Shadows (which is also awesome) largely because there isn’t much in the way of new live videos on YouTube yet.  That said, the track Gemini is one of my favorite off the album and if you’re looking to learn what Dream Pop is all about, this one nails it. If you dig the sound, check out more of their catalog and additionally the band Viiv. Viiv is opening for Wild Nothing on their current tour and I’m excited to report I’ll be seeing that billing live in DC at the Rock and Roll Hotel in September.

SeuratJS – A Raphaël plugin for creating beautiful pointillized animations.

So I’ve been bad about getting programming posts up lately, and my Zero to Ruby series has suffered from a bit of a hiatus. The good news is that it’s because I’ve been busy pushing out my first real open source effort: SeuratJS.

As the title explains SeuratJS is a plugin for the SVG drawing library Raphaël and it was largely inspired by the work I put in developing the header for this site.  The library runs entirely on the client side and can transform an image into a pointillized rendition.  More uniquely, the library makes it extremely easy to animate the resulting points allowing for effects ranging from gentle fade-ins to randomized splattering of color that would make Jackson Pollock proud.

The library was officially released on June 15th and I’ve been floored by the response it’s gotten so far. Between three days of front paging /r/programming and being featured on Web Resources Depot I’ve had close to 4500 unique hits.  I have a set of new features and suggestions that I’m excited to get into the library shortly and it looks like I’ll have some help from the GitHub community.

TLDR; I have been getting some Ruby in and have updates coming soon, but in the mean time I’ve been having a ton of fun with JavaScript.

The Format – The First Single

Something I feel like my generation largely takes for granted is how easy it is to learn about your favorite bands. Whereas our parents were stuck scrounging for articles in a few limited publications and picking through cover notes, with a simple Google search in the 21st century you can harvest an almost overwhelming amount of information. With the internet we have access to music blogs and Wikipedia pages, unreleased b-sides and covers, and footage of shows we couldn’t attend ourselves.

One byproduct of this, and particularly as cellphones have become increasing ubiquitous, is that you can watch a band grow up online. As I was picking through YouTube videos of the Format, I stumbled across a performance at Sacramento State University from 2004. For those of you who didn’t know the Format, you likely know Fun (Nate Ruess’ subsequent band) and their 20-something fist-pumping anthem ‘We are Young’. Now honestly Fun doesn’t do very much for me, but it is wild to see this band playing for such a meager crowd when its offshoot can sell out three nights of the Wiltmore in LA with its capacity of 1,850.

The song of the week is one of the tracks from the band’s ‘meager crowd’ era. The album it is off of, ‘Interventions and Lullabies’ would eventually go on to substantial popularity on the indie music scene, so in all reality this ‘era’ didn’t last long. ‘The First Single’ is the lead off track of the album and really gives a pretty good sense of the albums musical direction: acoustic guitars, clear and relaxed vocals, and a healthy dose of hand clapping.

While some people will lament the Format breaking up and Fun being more pop than indie-rock, as long as a band or musician is playing the music they love, I’m happy to see them enjoy success. Anyone who has played a half-empty bar or basement, even the musical purists, would be lying if they claimed they had never daydreamed about hearing themselves on the radio. It’s clips like this that give the rest of us hope.

From Zero to Ruby – Update 1

I’ll start off by saying that  Ruby has taken a bit of a back seat to putting the finishing touches on this site over the least couple week.  Because the blog is built on top of WordPress most of stylistic touches end up being PHP on the server side. It’s been ages since I’ve used PHP, so it’s never bad to brush up, but as I’ve been going back and forth between it and Ruby, I will say that it is much less… friendly?  In either case I’ve been able to put together a couple cool pieces of code that, once I clean up, I’ll share.

So as far as progress on the Ruby front:

 Books & Lessons

Rails Best Practices (Code School) – I’ve had a Code School account for awhile, and I really enjoyed Rails for Zombies (1 & 2) so I more less picked up where I left off.

 Meetups

Arlington RUG – “Ruby on Audio” – A couple really cool presentations on using Ruby to create music.  Both presenters were great, but I will say Joel Straight’s Ruby Drum Machine may have stolen the show.

Relevant Links

100 Vim Commands Every Programmer Should Know – While not expressly Ruby related, I’ve been using Vim for the last 6 months or so as my primary text editor.  I’m decent with the commands, but I want to start working in a larger set of them for day-to-day use.

I hope to ramp up my Ruby intake over the next couple weeks now that the bones of this blog are in place.  More updates to come!

The Gaslight Anthem – The ’59 Sound

I imagine the majority of albums and tracks I’m going to cover on this blog are going to fall into the category of ‘new music’.  But sometimes, a certain season, mood, or random seed reminds you of an old favorite.

The Gaslight Anthem’s ‘The 59 Sound’ is one of one of those favorites.  The album is 12 tracks of New Jersey born Americana that ooze with a grit and soul that would make Bruce Springsteen proud.  Perhaps then, it’s less surprising that the Gaslight Anthem spent 2009 touring in support of the Boss’ recent resurgence.  This pairing bolstered the band’s popularity and broadened its appeal from a younger generation, already wondering aloud if Brian Fallon, lead singer and songwriter, was rock & roll’s savior, to an older generation that, though likely incredulous, could connect back to a time when rock & roll didn’t need one.

I had the pleasure of seeing TGA play shortly after the release at the 9:30 Club in Washington, DC.  I wish I had known their material a little better before going to the show because the album is packed to the brim with anthems.  One real foot-stomper is the album’s namesake.  There are a number of great clips online of ‘The ‘59 Sound’ live, but this version from Glastonbury (with a special guest) may be most appropriate.

From Zero to Ruby (and Rails)

Over the last year or so I’ve dabbled in learning Ruby and Ruby on Rails.  Most of those attempts were one or two week long stints, and though these brief introductions have provided a superficial overview of the language, I’m a million  miles away from being able to call myself a Rubyist.

A bit back, I stumbled across an  article on Hacker News where a developer completely immersed himself in the language for a month.  Now a month isn’t a very long amount of time, especially with a full time job, but with a summer lull in grad school, I liked the idea enough that I’m committing to a similar regimen.

I’m going to spend the next 8 weeks consuming as much Ruby as I possibly can.  I’m going to provide weekly status updates to keep myself honest and to track my progress.  At the end of the 2 month stint I’m going to provide a breakdown of which books I thought were useful, any learning hacks I discover, and a compilation of resources I found to be useful.

I’ll provide my first update at the end of this weekend.  Wish me luck!

Lonely Forest – Turn Off This Song and Go Outside

After a winter that never came, a beautiful spring has arrived in Virginia.  With the warm weather, an apt single has started to receive spin on national alt stations.  Lonely Forest, a band from the small coastal town of Anacortes, Washington has been lighting up the radio waves with ‘Turn Off This Song and Go Outside’ from their 2011 release Arrows.

So turn off, turn off this song
find someone to love
turn off this song you can listen to it later
and go outside

The track is reminiscent of early Jimmy Eat World.  A brilliant hook and an atmospheric mixing deliver a sound that is able to offer nuance as well as the backdrop to your summer nights.  The video, which is filmed in Anacortes, captures the likely inspiration for the song and provides vibrant imagery that ties well.

Arrows is filled with many other strong tracks that capture the richness of the rural Pacific Northwest.  “Coyote” and “We Sing In Time” are worthy of a check out, though while you’re at it, I’d highly recommend giving the entire album a spin.

Of Monsters and Men – Little Talks

Finals are approaching, and that means I need some fresh music to ‘carry me’ through.  Last year I was lucky enough to stumble upon Wild Nothing’s – Gemini.  This year I’ve been  charmed by Nanna Bryndís Hilmarsdóttir and her infectious band Of Monsters and Men.

Now I wouldn’t describe myself as being into Icelandic Folk-Pop, but the band is  undeniably affable.  The dual vocals are done masterfully Nanna’s voice is breathy, yet bright, and her band mate Raggi’s is a smooth compliment.

Little Talk is the debut single off the band’s first EP – Into the Woods and is responsible for catapulting the band onto the international stage.

With an aggressive international touring schedule (I’m jealous of anyone who caught them at SXSW) and their newly released album ‘My Head is an Animal’ this band is almost guaranteed to explode over the next couple months.  In the mean time great tracks like ‘Mountain Sounds’ and ‘Your Bones’ will be the backdrop to my late nights of ‘Advanced AI’ and ‘Algorithms.’