java jackson serializer code example
Example 1: java json serializer
public class someClass {
//your lcode and logic...
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(MyAwesomeClass.class, new MyAwesomeSerializer());
mapper.registerModule(module);
jsonNode = mapper.convertValue(myAwesomeObject, JsonNode.class);
//... your code and logic
}
//serializer 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: jackson serialize xml
/**
* This function writes serializes the Java object into XML and writes it
* into an XML file.
*/
public static void serializeToXML() {
try {
XmlMapper xmlMapper = new XmlMapper();
// serialize our Object into XML string
String xmlString = xmlMapper.writeValueAsString(new PhoneDetails("OnePlus", "6.4", "6/64 GB"));
// write to the console
System.out.println(xmlString);
// write XML string to file
File xmlOutput = new File("serialized.xml");
FileWriter fileWriter = new FileWriter(xmlOutput);
fileWriter.write(xmlString);
fileWriter.close();
} catch (JsonProcessingException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
public static void main(String[] args) {
System.out.println("Serializing to XML...");
serializeToXML();
}