jackson serialize java code example
Example 1: java json serializer
public class someClass {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyAwesomeClass.class, new MyAwesomeSerializer());
mapper.registerModule(module);
jsonNode = mapper.convertValue(myAwesomeObject, JsonNode.class);
}
public class MyAwesomeSerializer extends StdSerializer<MyAwesomeClass> {
public MyAwesomeSerializer() {
super(MyAwesomeClass.class);
}
@Override
public void serialize(MyAwesomeClass myAwesomeClass, JsonGenerator jgen, SerializerProvider provider) throws IOException {
ObjectMapper mapper = new ObjectMapper();
jgen.writeStartObject();
jgen.writeStringField("name", myAwesomeClass.getName());
jgen.writeStringField("age", myAwesomeClass.getAge());
jgen.writeArrayFieldStart("hobbies");
for (Hobby hobby : myAwesomeClass.getHobbies()) {
jgen.writeObject(mapper.convertValue(hobby, JsonNode.class));
}
jgen.writeEndArray();
jgen.writeEndObject();
}
}
Example 2: java serialize object to json
public class someClass {
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyAwesomeClass.class, new MyAwesomeSerializer());
mapper.registerModule(module);
jsonNode = mapper.convertValue(myAwesomeObject, JsonNode.class);
}
public class MyAwesomeSerializer extends StdSerializer<MyAwesomeClass> {
public MyAwesomeSerializer() {
super(MyAwesomeClass.class);
}
@Override
public void serialize(MyAwesomeClass myAwesomeClass, JsonGenerator jgen, SerializerProvider provider) throws IOException {
ObjectMapper mapper = new ObjectMapper();
jgen.writeStartObject();
jgen.writeStringField("name", myAwesomeClass.getName());
jgen.writeStringField("age", myAwesomeClass.getAge());
jgen.writeArrayFieldStart("hobbies");
for (Hobby hobby : myAwesomeClass.getHobbies()) {
jgen.writeObject(mapper.convertValue(hobby, JsonNode.class));
}
jgen.writeEndArray();
jgen.writeEndObject();
}
}
Example 3: jackson serialize xml
public static void serializeToXML() {
try {
XmlMapper xmlMapper = new XmlMapper();
String xmlString = xmlMapper.writeValueAsString(new PhoneDetails("OnePlus", "6.4", "6/64 GB"));
System.out.println(xmlString);
File xmlOutput = new File("serialized.xml");
FileWriter fileWriter = new FileWriter(xmlOutput);
fileWriter.write(xmlString);
fileWriter.close();
} catch (JsonProcessingException e) {
} catch (IOException e) {
}
}
public static void main(String[] args) {
System.out.println("Serializing to XML...");
serializeToXML();
}