使用GSON进行Java到Json的验证 [英] Java to Json validation using GSON

查看:115
本文介绍了使用GSON进行Java到Json的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用GSON API将Java对象转换为Json字符串时,如果任何注释的属性为null,我也希望此Json转换失败。 例如 p>

  public class Order {

@SerializedName(orderId)
@Expose
@Required
私人整数ID;

// getter& setter for id
}

现在我正在做

  Order order = new Order(); 

JSONObject jsonobj = new JSONObject(gson.toJson(order));

如果任何@Required属性为空值$ b,我想要将上述Java转换为Json转换失败$ b是否可以使用GSON?

解决方案

如果任何Java属性为null,我想将Java转换为Json失败它被注释为@Required,
我可以使用以下方法实现此目的。如果您发现任何问题,请告诉我们:

  class RequiredKeyAdapterFactory implements TypeAdapterFactory {

public< T> TypeAdapter< T>创建(Gson gson,TypeToken< T>类型){

final TypeAdapter< T> delegate = gson.getDelegateAdapter(this,type);

返回新的TypeAdapter< T>(){
@Override
public void write(JsonWriter out,T value)抛出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);
}

私人< T> void validateNullValue(T value,Field field){
field.setAccessible(true);
Class t = field.getType();
Object v = null;
尝试{
v = field.get(value);
} catch(IllegalArgumentException | IllegalAccessException e){
抛出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 + 一片空白);
} else if(!t.isPrimitive()&& v == null){
throw new IllegalArgumentException(field +is null);



$ b @Override
public T read(JsonReader in)throws IOException {
return delegate.read(in);
}

};



RequiredKeyAdapterFactory requiredKeyAdapterFactory = new RequiredKeyAdapterFactory();
Gson gson = new GsonBuilder()。registerTypeAdapterFactory(requiredKeyAdapterFactory)
.create();

这是可行的


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

public class Order{

@SerializedName("orderId")
@Expose
@Required
private Integer id;

//getter & setter available for id
}

Now as I am doing

Order order = new Order();

JSONObject jsonobj = new JSONObject(gson.toJson(order));

I want to fail the above Java to Json transformation if any of the @Required attribute is null Is this possible using GSON?

解决方案

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

这篇关于使用GSON进行Java到Json的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆