Skip to content

Instantly share code, notes, and snippets.

@zspencer
Created April 19, 2010 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zspencer/371358 to your computer and use it in GitHub Desktop.
Save zspencer/371358 to your computer and use it in GitHub Desktop.
@XStreamAlias("Race")
public class Race {
@XStreamAlias("Name")
public String name;
@XStreamAlias("Drivers")
@XStreamImplicit
public List<Driver> drivers
public Race() {
drivers = new ArrayList<Driver>();
}
public String toJson() {
XStream xstream = new XStream(new JsonHierarchicalStreamDriver());
xstream.setMode(XStream.NO_REFERENCES);
xstream.processAnnotations(Race.class);
xstream.processAnnotations(Driver.class);
String jsonString = xstream.toXML(this);
return jsonString;
}
}
@XStreamAlias("Driver")
public class Driver {
public String name;
public Integer number;
}
import static org.junit.Assert.*;
import objects.Driver;
import objects.Race;
import org.junit.Test;
public class RaceTest {
@Test
public void testToJson() {
String expectedJsonString = "{\"Race\": {\n" +
" \"Name\": \"Another Right Turn!\",\n" +
" \"Drivers\": [ {\n" +
" \"name\": \"JimBob\",\n" +
" \"number\": 3\n" +
" },\n" +
" {\n" +
" \"name\": \"BimJob\",\n" +
" \"number\": 13\n" +
" } ]\n" +
"}}\n";
String actualString;
Race testRace = new Race();
testRace.drivers.add(new Driver("JimBob", 3));
testRace.drivers.add(new Driver("BimJob", 13));
testRace.name = "Another Right Turn!";
actualString = testRace.toJson();
assertEquals(expectedJsonString,actualString);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment