Java to Json validation using GSON

后端 未结 1 1341
闹比i
闹比i 2021-01-06 14:18

While converting Java object to Json string using GSON API, I also want to fail this Json conversion if any of the annotated attribute is null.

For example



        
相关标签:
1条回答
  • 2021-01-06 14:29

    I wanted to fail Java to Json conversion, if any of the Java attribute is null which is annotated as @Required, I am able to achieve this using following approach. Please let me know if you see any issues:

    class RequiredKeyAdapterFactory implements TypeAdapterFactory {
    
        public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    
            final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    
            return new TypeAdapter<T>() {
                @Override
                public void write(JsonWriter out, T value) throws IOException {
                    if (value != null) {
    
                        Field[] fields = value.getClass().getDeclaredFields();
    
                        for (int i = 0; i < fields.length; i++) {
                            if (fields[i]
                                    .isAnnotationPresent(Required.class)) {
                                validateNullValue(value, fields[i]);
                            }
    
                        }
                    }
                    delegate.write(out, value);
                }
    
                private <T> void validateNullValue(T value, Field field) {
                    field.setAccessible(true);
                    Class t = field.getType();
                    Object v = null;
                    try {
                        v = field.get(value);
                    } catch (IllegalArgumentException | IllegalAccessException e) {
                        throw new IllegalArgumentException(e);
                    }
                    if (t == boolean.class && Boolean.FALSE.equals(v)) {
                        throw new IllegalArgumentException(field + " is null");
                    } else if (t.isPrimitive()
                            && ((Number) v).doubleValue() == 0) {
    
                        throw new IllegalArgumentException(field + " is null");
                    } else if (!t.isPrimitive() && v == null) {
                        throw new IllegalArgumentException(field + " is null");
    
                    }
                }
    
                @Override
                public T read(JsonReader in) throws IOException {
                    return delegate.read(in);
                }
    
            };
        }
    }
    
    RequiredKeyAdapterFactory requiredKeyAdapterFactory = new RequiredKeyAdapterFactory();
    Gson gson = new GsonBuilder().registerTypeAdapterFactory(requiredKeyAdapterFactory)
            .create();
    

    This is working

    0 讨论(0)
提交回复
热议问题