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":"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}
Why fields id, name not exclude from json?