GSON equivalent for #JsonIgnoreProperties in Jackson - java

In Jackson you can ignore the properties by giving annotation #JsonIgnoreProperties at class level and the properties which are not in the actual JSON are not serialized/deserialized from/to the Java class. What is the equivalent of it if we are using GSON?

You can get a similar effect with the GSON #Expose annotation using GsonBuilder.excludeFieldsWithoutExposeAnnotation().
E.g.
public class User {
#Expose private String firstName;
#Expose(serialize = false) private String lastName;
#Expose (serialize = false, deserialize = false) private String emailAddress;
private String password;
}
If you use Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create() with the above class, then the toJson() and fromJson() methods will completely ignore the password field as it doesn't have an #Expose annotation.
(Note you also get finer-grained control here as you can control whether GSON serializes/deserializes fields as well).
Reference: https://github.com/google/gson/blob/master/UserGuide.md#TOC-Gson-s-Expose

In GSON, you can also declare the field as transient. It will have the same effect as opposite to marking other fields as #Expose. But, you will not have finer grained control of serialization/deserialization as that of #Expose. However, if you have 100s of fields spanned across multiple classes, and you only need to exclude one field, it is far more convenient to mark the field as transient. Moreover, this works on the default setting of GSON. E.g.
public class User {
String firstName;
String lastName;
private String emailAddress;
private transient String password;
}
Reference: https://github.com/google/gson/blob/master/UserGuide.md#finer-points-with-objects

Related

Hide sensitive data in an association relationship in java #JsonProperty

How can I hide some sensitive data on this example. I'm testing APIs in rest client (Postman), when I call Api List of Bills, I want to hide some data. In BillsDto I want to hide username, password and user age fields. Is it possible to do this in my BillsDto class (not in UserDto). I know I can hide some fields using #JsonProperty but how to do it for some fields belonging to another class?
***BillsDto***
public class BillsDto {
private String numberBills;
private double amount;
private Date deadlinePayment
private UserDto user; // try to hide username, password, age from BillsDto
}
***UserDto***
public class UserDto {
private String number_id;
private String username;
private String password;
private String firstName;
private String lastName;
private String age;
}
I know I can hide some fields using #JsonProperty but how to do it for some fields belonging to another class?
The fact that you're using UserDto as a nested object somewhere, doesn't change the serialization policy that you can express through data binding annotations in the UserDto.
If you can change UserDto, apply #JsonProperty with it's property access set to JsonProperty.Access.WRITE_ONLY on the fields want to hide during serialization.
public class UserDto {
private String number_id;
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String username;
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;
private String firstName;
private String lastName;
#JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String age;
}
If for some reason, you want to achieve this by editing BillsDto only, then you can implement a custom serializer for UserDto and apply it by making use of the #JsonSerialize. But to ensure that you're not disclosing the sensitive data somewhere, it would be better to apply this policy in one place - in the UserDto, because you or one of your colleagues might simply forget to #JsonSerialize in some of the classes which uses UserDto.

Should a Class which is serialzied with GSON to JSON implemet the Serializable Interface

I have this POJO which is being serialzied to JSON using new Gson().toJson(entity)
Should I implement the Serializable Interface on this POJO?
#Data
public class BankcodeJSONEntity {
#NotNull
#Size(min = 8, max = 8)
private String bankcode;
#NotNull
#Size(min = 11, max = 11)
private String bic;
#NotNull
private String ticket;
#Basic
#Temporal(TemporalType.DATE)
#NotNull
private Date date;
#NotNull
private String category;
#NotNull
private String name;
}
No, it is not necessary. Gson use reflection in order to produce the desired json. You should implements Serializable when:
save it on disk
send it through a socket as an Object
For example, if you have a web application deployed in HA on two or more nodes in cluster (then they exchange the session each other), and you use a session scope to save user authentication, the bean that contains this information must be serializable.
If you decide to use Serializable add a serialVersionUID. This is a long used by the JVM to identify in an unique manner the object itself.
When you don't sepcify it, the compiler add a generated one (that is therefore compiler dependent) and this identity changes when you change your object, for example adding a field; this means that after a minimal change, you shouldn't deserialize objects serialized before the change.

Spring MongoDB - Difference between #Indexed and #Field annotations

I am trying to understand how the two different annotations of #Indexed and #Field differ while defining a model in Java Spring Boot.
public class Notation {
#Id
private String id;
#Field("value")
private String value;
#Field("description")
private String description;
#Field("frequency")
private int frequency;
}
public class Notation {
#Id
private String id;
#Indexed("value")
private String value;
#Indexed("description")
private String description;
#Field("frequency")
private int frequency;
}
My use case is to finally implement a search from the repository based on both value and description fields, so it would be good to get an idea of how the data is structured in the two and what are the various options one can use from these annotations.
#Indexed annotation is will add an index that on that field in your mongo server. It takes an optional string parameter, which will be the index name and nothing to do with the field name. You should have only those fields indexed which will be used for filtering out documents.
#Field is used if you want to have different names in your java code and MongoDB collection.
For eg.
#Field("desc")
private String description;
In this case, in your MongoDB collection, you will find field name as "desc" while in your java code you will be referencing it as "description"
#Field("description")
private String description;
In the above case, there is no need for using #Field annotation

How to serialize values which are provided JsonInclude.Include.NON_NULL at class level

Currently my application has a class which is as below
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Employee {
Department department;
String firstName;
String lastName;
String address;
String phoneNumber;
}
I am capturing the employee object inside the logs where I am converting the object into JSON. I am able to convert the object to JSON but the null values do not get into the JSON.
I have tried the below
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
generator.setCodec(objectMapper);
generator.writeObjectField(fieldName, argument);
But not able to get the null values of the fields in JSON. How do I get them?
You can copy an ObjectMapper and change some of its options, in this case you can ignore annotations:
ObjectMapper mapperIgnoringAnnotations = mapper.copy()
.disable(MapperFeature.USE_ANNOTATIONS)
.setSerializationInclusion(JsonInclude.Include.ALWAYS)
.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
Then use this modified ObjectMapper to serialize this class but the standard one for the other classes. Not convenient if Employee has many other annotations that you want to take into account.
USE_ANNOTATIONS

Ignore Java Object's Selected fields while Sending it as JSON

I am new to Spring-MVC.
I am sending data to my view as JSON, and there I am deserializing it to a string, but I want to pass only selected fields, I don't want all fields to send there but how to ignore selected fields I don't know.
My class POJO code :
public class account{
private Integer userId;
private String userName;
private String emailId;
//getter - setter
}
In some activity I don't want some fields so I want to avoid that fields so any idea on this confusing situation ?
Add the annotation #JsonIgnoreProperties("fieldname") to your POJO.
or you can use #JsonIgnore also before field name that you want to ignore while deserializing JSON.
example :
#JsonIgnore
#JsonProperty(value = "user_password")
public java.lang.String getUserPassword()
{
return userPassword;
}
Here Is my Answer for Similar Question.

Categories