Skip to content

Instantly share code, notes, and snippets.

@vakho10
Created June 11, 2018 08:08
Show Gist options
  • Save vakho10/bb8c27fa1d3d6081e5e9909f58479a02 to your computer and use it in GitHub Desktop.
Save vakho10/bb8c27fa1d3d6081e5e9909f58479a02 to your computer and use it in GitHub Desktop.
Simple JSON Serializer (from Object to JSON).
package ge.tsu.serializer.json;
import java.lang.reflect.Field;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.Temporal;
public class JsonSerializer {
public static void main(String... args) throws Exception {
Author[] authors = {
new Author("Hiroshi", "Sakurazaka", LocalDate.of(1970, 1, 1), false),
new Author("Vakhtangi", "Laluashvili", LocalDate.of(1993, Month.MAY, 14), false),
};
Book book = new Book("All You Need is Kill", authors, 2004);
String json = toJson(book, Book.class);
System.out.println(json);
}
public static String toJson(Object obj, Class<?> clazz) throws Exception {
StringBuilder sb = new StringBuilder();
if (clazz.isArray()) {
sb.append("[");
Object[] objects = (Object[]) obj;
int idx = 0;
for (Object o : objects) {
sb.append(toJson(o, o.getClass()));
if (idx < objects.length - 1) {
sb.append(",");
}
++idx;
}
sb.append("]");
} else {
sb.append("{");
Field[] fields = clazz.getDeclaredFields(); // get all fields for current class
int idx = 0;
for (Field field : fields) {
// Serialize name
String name = field.getName();
sb.append("\"").append(name).append("\":");
// Serialize value
Object value = field.get(obj);
// Serialize sub-objects
// but not 'Strings', 'primitive', or 'date types'!
if (Object.class.isInstance(value)
&& !String.class.isInstance(value)
&& !Temporal.class.isInstance(value)
&& !field.getType().isPrimitive()) {
sb.append(
toJson(value, field.getType())
);
} else {
// wrap value in quotes if not a JSON object or array
sb.append("\"").append(value).append("\"");
}
if (idx < fields.length - 1) {
sb.append(",");
}
++idx;
}
sb.append("}");
}
return sb.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment