gpt4 book ai didi

java - 为什么自定义@Exclude不从序列化中排除字段

转载 作者:行者123 更新时间:2023-12-01 17:06:33 26 4
gpt4 key购买 nike

将对象序列化/反序列化为 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 {}

用途:

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":"admin@admin.com","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}

为什么字段 id, name 不从 json 中排除?

最佳答案

您可能需要为此编写自定义 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)

此处,如果序列化为 true,则在序列化时将标记的字段写到 JSON 中。

如果 deserialize 为 true,则将从 JSON 中反序列化标记字段。和

Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();

稍后您可以执行 gson.toJson(product)

编辑:如果 Gson 对象被创建为 new Gson() 并且如果我们尝试执行 toJson() 和 fromJson() 方法,则 @Expose 对序列化和反序列化没有任何影响。

关于java - 为什么自定义@Exclude不从序列化中排除字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61460583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com