当serializedeserialize对象为json时,我需要排除特定的字段。
我创建了我的自定义注解。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {}
Use:
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.Set;
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Exclude
private int id;
@NotNull
@Exclude
private String name;
这里用Gson序列化:
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
JsonObject json = new JsonObject();
json.addProperty("user_name", currentUserName);
Product product = productEntry.getProduct();
json.addProperty("product", GsonUtil.gson.toJson(product));
json.addProperty("quantity", productEntry.getQuantity());
logger.info("addProductToCart: json = " + json);
这里是结果:
addProductToCart: json = {"user_name":"[email protected]","product":"{\"id\":0,\"name\":\"My product 1\",\"description\":\"\",\"created\":\"Apr 27, 2020, 4:53:34 PM\",\"price\":1.0,\"currency\":\"USD\",\"images\":[\"url_1\",\"url_2\"]}","quantity":1}
为什么字段 身份证、姓名 不从json中排除?
Gson可以理解 @Expose(serialize = false)
注释。
import com.google.gson.annotations.Expose;
@Expose(serialize = false)
private int id;
}
你可能需要为此编写自定义的json序列化器,如下所示。
class ExcludeFieldsSerializer extends JsonSerializer<Bean> {
@Override
public void serialize(final Bean value, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException {
gen.writeStartObject();
try {
for (final Field aField : Bean.class.getFields()) {
if (f.isAnnotationPresent(Ignore.class)) {
gen.writeStringField(aField.getName(), (String) aField.get(value));
}
}
} catch (final Exception e) {
}
gen.writeEndObject();
}
}
使用你的对象映射器来注册相同的
然而,您也可以使用现有的注释作为
@Expose (serialize = false, deserialize = false)
如果serialize为真,那么在序列化的同时,标记的字段会被写入JSON中。
如果deserialize为true,则标记的字段将从JSON中反序列化。
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
之后你可以做 gson.toJson(product)
编辑:如果Gson对象被创建为new Gson(),如果我们尝试执行toJson()和fromJson()方法,那么@Expose对序列化和反序列化没有任何影响。
我找到了解决方案。
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Exclude {}
在初始化gson的时候
public class GsonUtil {
public static GsonBuilder gsonbuilder = new GsonBuilder();
public static Gson gson;
public static JsonParser parser = new JsonParser();
static {
// @Expose -> to exclude specific field when serialize/deserilaize
gsonbuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes field) {
return field.getAnnotation(Exclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
});
gson = gsonbuilder.create();
}
}
使用。
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Exclude
private int id;
现在成功EXCLUDE特定领域。