Skip to content

Instantly share code, notes, and snippets.

@bbakerman
Created April 19, 2020 01:19
Show Gist options
  • Save bbakerman/2506134e3614f8da8eca5fd1036464d6 to your computer and use it in GitHub Desktop.
Save bbakerman/2506134e3614f8da8eca5fd1036464d6 to your computer and use it in GitHub Desktop.
public class TestJackson {
static class User {
String name;
int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
public static class UserSerializer extends StdSerializer<User> {
public UserSerializer() {
this(null);
}
public UserSerializer(Class<User> t) {
super(t);
}
@Override
public void serialize(User value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField("name", value.name);
jgen.writeNumberField("age", value.age);
jgen.writeEndObject();
}
}
static class StatefulJsonGenerator extends JsonGeneratorDelegate {
public StatefulJsonGenerator(JsonGenerator d) {
super(d);
}
}
@Test
public void jackson() throws IOException {
StringWriter sw = new StringWriter();
User brad = new User("brad", 50);
SimpleModule testModule = new SimpleModule("CustomModule", new Version(1, 0, 0, null, "gid", "aid"));
testModule.addSerializer(new UserSerializer(User.class));
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(testModule);
JsonFactory jsonFactory = objectMapper.getFactory();
JsonGenerator writerJsonGenerator = jsonFactory.createGenerator(sw);
JsonGenerator jsonGenerator = new StatefulJsonGenerator(writerJsonGenerator);
objectMapper.writeValue(jsonGenerator, brad);
System.out.println(sw);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment