Reputation: 15726
I need to exclude specific fields when serialize/deserialize object to json.
I create my custom annotation:
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;
And here serialize by 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);
and here result:
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}
Why fields id, name not exclude from json?
Upvotes: 0
Views: 339
Reputation: 15726
I found solution:
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 {}
and when init 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();
}
}
Use:
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Exclude
private int id;
and now success EXCLUDE specific field.
Upvotes: 0
Reputation: 549
you might need to write your custom json serializer for this as follows:
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();
}
}
use your object mapper to register the same
However, you can also use existing annotations as
@Expose (serialize = false, deserialize = false)
Here if serialize is true then marked field is written out in the JSON while serializing.
if deserialize is true, hen marked field is deserialized from the JSON. and
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
Later you can do gson.toJson(product)
Edit : if Gson object is created as new Gson() and if we try to execute the toJson() and fromJson() methods then @Expose does not have any effect on serialization and deserialization.
Upvotes: 1
Reputation: 4045
Gson understands @Expose(serialize = false)
annotation,
import com.google.gson.annotations.Expose;
@Expose(serialize = false)
private int id;
}
Upvotes: 0