0

我有下面这3种方法。我只是不知道将它们作为一个整体,因为它们是数组、列表或只是一个对象的类型。这些方法只是将给定对象转换为 json 字符串,然后将其转换为给定的指定类。

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;
}
4

1 回答 1

0

基本上,您可以编写一个包含对象类型的某些情况的方法,如以下几行。

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);
        }
    }
}
于 2018-04-13T11:28:39.770 回答