0

I have these 3 methods below. I only don't have a clue to make them as one, as they are type of array, list or just an object. These methods just convert a given object to a json string and then convert it to the specified class that was given.

public static List<Object> objectListSerializer(List<Document> documents, Class entity) {
    List<Object> entityList;

    String json = com.mongodb.util.JSON.serialize(documents);

    entityList = (List<Object>) GSON_INSTANCE.fromJson(json, entity);

    return entityList;
}

public static Object objectArraySerializer(Object objectArray, Class clazz) {
    String jsonString = GSON_INSTANCE.toJson(objectArray);

    Object convert[] = (Object[]) GSON_INSTANCE.fromJson(jsonString, clazz);

    return convert;

}


public static Object objectSerializer(Object object, Class clazz) {
    String jsonString = GSON_INSTANCE.toJson(object);

    Object convert = GSON_INSTANCE.fromJson(jsonString, clazz);

    return convert;
}
  • 1
    use `interface` and `generics` for different implementation. – msagala25 Apr 13 '18 at 08:29
  • 2
    And hint: follow the java naming conventions. Method names go with verbs first of all. And then your names are **very** misleading. You are serializing content as JSON, to then **de-serialize** that JSON? Reading your method names, that is **not at all** clear. – GhostCat Apr 13 '18 at 08:32
  • @GhostCat yes, thank you for pointing that out for me. I am confusing myself with these namings – LaurentKavaba Apr 13 '18 at 08:35
  • 1
    IMHO if you'r return type of any method is an `Object`, you should consider to rethink your code design. – zlakad Apr 13 '18 at 08:35

1 Answers1

0

Basically, you can write a method that includes the some cases of object type like the following lines.

public static Object serialize(Object object, Class<?> entity) {
    String jsonString = null;

    if (object instanceof List) {    
        jsonString = com.mongodb.util.JSON.serialize((List<?>) object);
        return (List<?>) GSON_INSTANCE.fromJson(jsonString, entity);
    } else {
        jsonString = GSON_INSTANCE.toJson(object);

        if (object.getClass().isArray()) {
            return (Object[]) GSON_INSTANCE.fromJson(jsonString, entity);
        } else {
            return GSON_INSTANCE.fromJson(jsonString, entity);
        }
    }
}
adilkun
  • 41
  • 3
  • Would you say this is a good practice?, referring to the comments at my post? I don't have a good understanding of this generics and did not seem to figure it out with the "Box" example from Oracle. – LaurentKavaba Apr 13 '18 at 12:06
  • If you would like to use only one method, I think this practice is good for you. It's the simplest practice. – adilkun Apr 13 '18 at 13:57