|
| 1 | +package com.baeldung.customannotations; |
| 2 | + |
| 3 | +import java.lang.reflect.Field; |
| 4 | +import java.lang.reflect.InvocationTargetException; |
| 5 | +import java.lang.reflect.Method; |
| 6 | +import java.util.HashMap; |
| 7 | +import java.util.Map; |
| 8 | +import java.util.Objects; |
| 9 | +import java.util.stream.Collectors; |
| 10 | + |
| 11 | +public class ObjectToJsonConverter { |
| 12 | + public String convertToJson(Object object) throws JsonSerializationException { |
| 13 | + try { |
| 14 | + |
| 15 | + checkIfSerializable(object); |
| 16 | + initializeObject(object); |
| 17 | + return getJsonString(object); |
| 18 | + |
| 19 | + } catch (Exception e) { |
| 20 | + throw new JsonSerializationException(e.getMessage()); |
| 21 | + } |
| 22 | + } |
| 23 | + |
| 24 | + private void checkIfSerializable(Object object) { |
| 25 | + if (Objects.isNull(object)) { |
| 26 | + throw new JsonSerializationException("Can't serialize a null object"); |
| 27 | + } |
| 28 | + |
| 29 | + Class<?> clazz = object.getClass(); |
| 30 | + if (!clazz.isAnnotationPresent(JsonSerializable.class)) { |
| 31 | + throw new JsonSerializationException("The class " + clazz.getSimpleName() + " is not annotated with JsonSerializable"); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + private void initializeObject(Object object) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { |
| 36 | + Class<?> clazz = object.getClass(); |
| 37 | + for (Method method : clazz.getDeclaredMethods()) { |
| 38 | + if (method.isAnnotationPresent(Init.class)) { |
| 39 | + method.setAccessible(true); |
| 40 | + method.invoke(object); |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + private String getJsonString(Object object) throws IllegalArgumentException, IllegalAccessException { |
| 46 | + Class<?> clazz = object.getClass(); |
| 47 | + Map<String, String> jsonElementsMap = new HashMap<>(); |
| 48 | + for (Field field : clazz.getDeclaredFields()) { |
| 49 | + field.setAccessible(true); |
| 50 | + if (field.isAnnotationPresent(JsonElement.class)) { |
| 51 | + jsonElementsMap.put(getKey(field), (String) field.get(object)); |
| 52 | + } |
| 53 | + } |
| 54 | + |
| 55 | + String jsonString = jsonElementsMap.entrySet() |
| 56 | + .stream() |
| 57 | + .map(entry -> "\"" + entry.getKey() + "\":\"" + entry.getValue() + "\"") |
| 58 | + .collect(Collectors.joining(",")); |
| 59 | + return "{" + jsonString + "}"; |
| 60 | + } |
| 61 | + |
| 62 | + private String getKey(Field field) { |
| 63 | + String value = field.getAnnotation(JsonElement.class) |
| 64 | + .key(); |
| 65 | + return value.isEmpty() ? field.getName() : value; |
| 66 | + } |
| 67 | +} |
0 commit comments