Annotation JsonSerializable /create and put a json file in a new directory/

Viewed 5

I need to create a JsonSeriazable annotation that receives a directory where the Json file will be located after serialization. Any ideas how can I do that?

public class Main {
    public static void main(String[] args) throws IllegalAccessException {
        Product product1 = new Product("Samsung", 1000, "Smartphone");     
        new JsonSerializer<Product>().serialize(product1);
    }
}___________________________________________________________
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;

public class JsonSerializer<T>{
    public void serialize(T obj) throws IllegalAccessException {
        Class classObj = obj.getClass();
        if (!classObj.isAnnotationPresent(JsonSerializable.class)) {
            System.out.println("This object doesn't have @JsonSerializable annotation");
        } else {
            String json = "";
            Field[] fields = classObj.getDeclaredFields();
            for (Field field : fields) {
                String fieldName = field.getName();
                field.setAccessible(true);
                String value = field.get(obj).toString();
                json += fieldName + ":" + value + ",";
                field.setAccessible(false);
            }
            json = "{" + json.substring(0, json.length() - 1) + "}";
            System.out.println(json);
            String path = classObj.getName().toLowerCase() + ".json";
            try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path))) {
                oos.writeObject(obj);
                System.out.println("File has been written in the new directory 'JsonFiles' ");
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }}}}
__________________________________________________________________________________________________

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonSerializable {
    public String directory() default  "JsonFiles";

}

Right now, the program does serialiation, shows the result in the console and puts the file in the project directory.

0 Answers
Related