Skip to content

Instantly share code, notes, and snippets.

@eleco
Created November 17, 2013 15:47
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 eleco/7514775 to your computer and use it in GitHub Desktop.
Save eleco/7514775 to your computer and use it in GitHub Desktop.
json builder
public class Builder {
private String name;
private String description;
public Thing build(){
return new Thing(name, description);
}
public Builder withName(String name){
this.name = name;
return this;
}
public Builder withDescription(String description){
this.description = description;
return this;
}
}
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class BuilderTest{
@Test
public void testBuilder(){
Thing aThing = new Builder().withName("aname").withDescription("somedesc").build();
assertThat(aThing.getDescription(),is("somedesc"));
assertThat(aThing.getName(), is("aname"));
}
}
import org.codehaus.jackson.map.ObjectMapper;
import java.io.IOException;
public class JsonBuilder {
private Thing thing =null;
public Thing build(){
return thing;
}
public JsonBuilder add(String s) throws IOException {
this.thing = new ObjectMapper().readValue(convertToJson(s), Thing.class);
return this;
}
private String convertToJson(String nvps){
String json = nvps.replaceAll("([A-za-z0-9.]+)","\"$1\"");
json = "{" + json + "}";
return json;
}
}
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public class JsonBuilderTest {
@Test
public void testJsonBuilder() throws Exception{
Thing aThing = new JsonBuilder().add("name:aname,description:somedesc").build();
assertThat(aThing.getDescription(),is("somedesc"));
assertThat(aThing.getName(),is("aname"));
}
}
class Thing
{
private String name;
private String description;
public Thing(){}
public Thing(String name, String description){
this.name = name;
this.description = description;
}
public String toString(){
return String.format("name:%s description:%s", name, description);
}
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
String getDescription() {
return description;
}
void setDescription(String description) {
this.description = description;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment