Remove a field from entity when passing to Jersey + Jackson - java

I'm using Jersey + Jackson (built in in Dropwizard) to create a series of web services. I directly map objects in Json by passing them to Response object in Jersey:
myObject object = new myObject(fields...);
return Response.ok(object).build();
Fields are correctly annotated in myObject class with JsonProperty("fieldName").
But, in case I have a field that I need to store to database (ex: a password hash), but I do not want to pass in request responses, how can I remove that field when passing the entity to Response object?
I can't annotate the field with JsonIgnore, otherwise that field won't be serialized at all when I map the Json to database (ElasticSearch).

One option is to simply set the field to null. To configure the ObjectMapper to ignore the field in the JSON altogether when the field is null, you can just do
#Override
public void run(YourConfiguration configuration,
Environment environment) throws Exception {
...
environment.getObjectMapper().setSerializationInclusion(Include.NON_NULL);
}
As an aside, this security reason a one of the reasons to use DTOs (data transfer objects), an extra entity "view" layer that separates the representation we send out from the persistence layer (db entity object). It may seem redundant to create another object with the same/similar attributes, but the security padding is worth it.
Also, though not an official release yet, Dropwizard 0.8.0 uses Jersey 2, which introduced Entity Filtering, which allows us filter out the data we don't want sent out, without the need to create DTOs. Just thought I'd mention it.

You should use both JsonIgnore and JsonProperty to achieve this.
public class User {
private String name;
private String password;
#JsonProperty
public void setPassword(String password) {
this.password = password;
}
#JsonIgnore
public String getPassword() {
return this.password;
}
}
#JsonProperty on setter method will be used in serialization & JsonIgnore on getter method will be used in deserialization.

Actually #Manikandan answer should work for you. See Only using #JsonIgnore during serialization, but not deserialization
In worst case you may try to implement JsonSerializer.
public class MyObjectSerializer extends JsonSerializer<MyObject> {
#Override
public void serialize(MyObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
jgen.writeStartObject();
jgen.writeString(value.getField1());
jgen.writeString(value.getField2());
/* and not include field that you don't want to serialize */
jgen.writeEndObject();
}
}
#JsonSerialize(using = MyObjectSerializer.class)
public class MyObject {
String field1;
Integer field2;
String fieldNotToBeSerialized;
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public Integer getField2() {
return field2;
}
public void setField2(Integer field2) {
this.field2 = field2;
}
public String getFieldNotToBeSerialized() {
return fieldNotToBeSerialized;
}
public void setFieldNotToBeSerialized(String fieldNotToBeSerialized) {
this.fieldNotToBeSerialized = fieldNotToBeSerialized;
}
}

Related

Is it possible to map a JPA/Hibernate Entity field to a field in another class without #Embeddable?

I have a very simple Entity (Person.java) that I am wanting to persist via JPA/Hibernate.
The Entity contains two fields: ID and Identification String.
The ID is a simple Integer, and is no problem. The Identification String is currently a String, but for various reasons, I want to instead use a wrapper class for String (IDString), where there are various validation methods among other things.
I am wondering how I can get JPA/Hibernate to use the wrapped string (inside the custom class IDString) when persisting the Person table in the database. I know this can probably be solved by letting the IDString be #Embeddable and then embed IDString in the Person entity with #Embedded, but I am looking for another method, mostly because IDString is in an entirely different package, and I am reluctant to have to go there and change stuff.
Googling, I found https://www.baeldung.com/hibernate-custom-types, but it seems to be mostly about more complicated cases, where you want to convert one class into another type, and I do feel that there is probably a smarter way that I am simply overlooking.
Here is the entity (in theory)
#Entity(name="Person")
#Table(name="DB_TABLE_PERSON")
public class Person implements Serializable {
#Id
Integer id;
// WHAT SHOULD I PUT HERE? I WANT TO SIMPLY USE THE STRING INSIDE IDSTRING AS THE FIELD TO PERSIST
IDString idString;
// getter and setter for ID.
public void getIdString() {
return idString.getValue();
}
public void setIdString(String in) {
idString.setValue(in);
}
}
And here is the class IDString (in theory):
public class IDString {
// I really want to be a POJO
private final String the_string;
public IdString(String input) {
if (isValid(input)) {
the_string = input;
} else {
throw new SomeCoolException("Invalid format of the ID String");
}
public boolean isValid(String input) {
// bunch of code to validate the input string
}
public String getValue() {
return the_string;
}
public void setValue(String input) {
if (isValid(input)) the_string = s;
else throw new SomeCoolException("Invalid format of the ID String");
}
I know that I could place the validation if the IDString inside the Entity, but the IDString will be used elsewhere (it's a general custom class), so I don't want to do that. Is there a simple way?
#Converter(autoApply=true) // autoApply is reasonable, if not use #Converter on field
public class IDStringConverter implements AttributeConverter<IDString,String> {
#Override
public String convertToDatabaseColumn(IDString attribute) {
return attribute != null ? attribute.getValue() : null;
}
#Override
public IDString convertToEntityAttribute(String dbData) {
return dbData != null ? new IDString(dbData) : null;
}
}
With this you should not need any other modifications in your code. One limitation of the AttributeConverter is that it maps from exactly 1 Java field to exactly 1 DB column. If you wanted to map to more columns (not the case here), you would need embeddables.
You could also put a #Column annotation on the getter:
#Entity
public class Person {
private final IdString idString = new IdString();
#Column(name = "ID_STRiNG")
public IdString getIdString() {
return idString.getValue();
}
public void setIdString(String input) {
idString.setValue(input);
}
Another solution could be to convert to/from IdString using #PostLoad and #PrePersit event handlers:
#Entity
public class Person {
#Column(name = "ID_STRiNG")
private String the_string; // no getters & setters
#Transient
private final IdString idString = new IdString();
#PostLoad
public void postLoad() {
idString.setValue(the_string);
}
#PrePersist
public void prePersist() {
the_string = idString.getValue();
}
// getters & setters for idString

Java Spring custom Enum to String conversion in JSON Serialization

I'm trying to convert an enum value into a custom string as part of a JSON response in a Java Spring application. I've attempted to override the enum's toString method and create a Spring converter but both attempts don't seem to work.
Sample Controller
#RequestMapping(value = "/test/endpoint", produces = APPLICATION_JSON_VALUE)
#RestController
public class RecommenderController {
...
#GetMapping("test")
public List<MyEnum> test() {
return new ArrayList<>() {{
this.add(MyEnum.SAMPLE);
}};
}
}
Enum
public enum MyEnum {
SAMPLE("sample"), OTHER_SAMPLE("other sample");
private final String name;
public MyEnum(String name) {
this.name = name;
}
public String toString() {
return this.name;
}
}
This code returns the response ["SAMPLE"] although I want it to return ["sample"]. Is there a way to implement this in Spring?
Assuming you are using the default MappingJackson2HttpMessageConverter, then behind the scenes you are using Jackson's ObjectMapper to perform all the JSON serialization and deserialization. So it's a matter of configuring Jackson for your protocol objects.
In this case, it's probably most straightforward tell Jackson that it can make a single JSON value for your instance of MyEnum with the #JsonValue annotation.
public enum MyEnum {
SAMPLE("sample"), OTHER_SAMPLE("other sample");
private final String name;
public MyEnum(String name) {
this.name = name;
}
#JsonValue
public String getValue() {
return this.name;
}
}
#JsonValue has a bonus, as described in its Javadoc:
NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization.
So if you have the same Enum definition in your application that receives the list, it will deserialize the human readable value back into your Enum.
This can be done by using the #JsonValue annotation in the enum definition:
public enum MyEnum {
...
#JsonValue
public String getName() {
return this.name;
}
}

Is there a way to upper case a JSON value before binding it - using SpringBoot?

I am working on a SpringBoot REST service. The REST service works when the UI sends the right JSON values (formatted).
Sometimes the UI team will forget to upper case a property value and cause an exception. I want to make the REST service handle such cases.
JSON property is being POSTed as
"category":"patient"
It is supposed to be POSTed with uppercase.
"category":"PATIENT"
The Java object property category is a ENUM
public enum StaffCategory {
PATIENT, EQUIPMENT
}
The ui model object
#JsonProperty("category")
private StaffCategory category;
#JsonProperty("category")
public StaffCategory getCategory() {
return category;
}
#JsonProperty("category")
public void setCategory(StaffCategory category) {
this.category = category;
}
#JsonProperty("category")
private StaffCategory category;
This is the error I get
Can not deserialize value of type model.constants.StaffCategory
from String "patient": value not one of declared Enum instance names: [PATIENT, EQUIPMENT]
Although UI team should stick to backend API specs, still you can use ObjectMapper configuration to overcome this specific scenario:
#Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS, true);
return mapper;
}
You dont need to convert it to uppercase because it lowers readability and also avoids maintainability.You only need to change your Enum definition as:
public enum StaffCategory {
PATIENT("patient"), EQUIPMENT("equipment");
private String value;
private StaffCategory(String value) { this.value = value; }
#JsonValue
public String getValue() { return this.value; }
}
This way it get easily deserialized with no breaking your code or facing any problems.

Using Spring #RequestBody to convert JSON with mixed convention in payload to Entity Object

I am using Spring #RequestBody to map a JSON payload to a Java Object. Unfortunately this JSON payload does not use a set convention but rather has names that use both camelCase and snake_case.
To be clear my Controller looks like this:
#RequestMapping(value="/mobile/device", method = RequestMethod.PUT)
public ResponseEntity<Object> flagDevice (#RequestBody List<MobileDeviceData> deviceInfoList) {
... code here ...
}
with the MobileDeviceData Entity object having several setter methods like:
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public void setFlagId(int flagId) {
this.flagId = flagId;
}
This works great and without any extra effort when the JSON objects name is camelCase. However for snake_case names I need to add the Annotation:
#JsonProperty("flag_id")
private int flagId;
in order for it to be picked up.
I know it's not a good idea to use the #JsonProperty if it can be avoided as you then will need to annotate every parameter. My question is, is there a more general way to enforce matching snake_case with the corresponding camelCase in the Entity object? And obviously to do it without screwing up the ones that are already camelCase.
As per the article here, there is a simple approach to deserialize the MobileDeviceData class. Here is the sample code as below:
#JsonDeserialize(using = UserDeserializer.class)
public class User {
private ObjectId id;
private String username;
private String password;
public User(ObjectId id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public ObjectId getId() { return id; }
public String getUsername() { return username; }
public String getPassword() { return password; }
}
Assume User is the class we’re interested in writing the Deserializer for. Not much is notable here, except for the annotations that tell Jackson who knows how deserialize this class.
public class UserDeserializer extends JsonDeserializer {
#Override
public User deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext) throws IOException {
ObjectCodec oc = jsonParser.getCodec();
JsonNode node = oc.readTree(jsonParser);
return new User(null,
node.get("username").getTextValue(),
node.get("password").getTextValue());
}
}
The deserializer is created by extending Jackson’s abstract JsonDeserializer class, and giving it the type we want to deserialize to. Difficult is figuring out that you can reference the JSON by field name with the JsonParser's ObjectCodec.
I hope it helps.
Please feel free to comment if needed!
Having been working on this a bit, I now realize doing anything like what was requested would be counterproductive.
When you receive (deserialize) a JSON Object, it is generally expected that you will deliver (serialize) with the same parameters. If an implementation extracted both camelCase and underscore parameters the same way, then it would not know how to deserialize correctly later on. By following a standard convention and then using #JsonProperty for all the exceptions, it remains possible to deserialize and later deliver the JSON object just as it was received.

How does the Jackson mapper know what field in each Json object to assign to a class object?

Let's say I have a Json object like this:
{
"name": "Bob Dole",
"company": "Bob Dole Industries",
"phone": {
"work": "123-456-7890",
"home": "234-567-8901",
"mobile": "345-678-9012"
}
}
And to help me read it, I use Jackson's Object Mapper with the following class:
public class Contact {
public static class Phone {
private String work;
private String home;
private String mobile;
public String getWork() { return work; }
public String getHome() { return home; }
public String getMobile() { return mobile; }
public void setWork(String s) { work = s; }
public void setHome(String s) { home = s; }
public void setMobile(String s) { mobile = s; }
}
private String name;
private String company;
private Phone phone;
public String getName() { return name; }
public String getCompany() { return company; }
public Phone getPhone() { return phone; }
public void setName(String s) { name = s; }
public void setCompany(String s) { company = s; }
public void setPhone(Phone p) { phone = p; }
}
My question is, how (using the simplest explanation possible), does the Object mapper "deserialize" the Json object? I thought it was matching variable names, but changing them by a few letters didn't affect the output. Then, I tried switching the order of the set() functions, but that didn't do anything. I also tried both, but that was also useless. I'm guessing there's something more sophisticated at work here, but what?
I tried to look in the documentation and past code, but I didn't see an explanation that made sense to me.
Without Annotations:
Without any annotations, it does what is called POJO mapping, it just uses reflection on the instance members and uses some rules about how to map the keys in the json to the names of the instance members. *note: it works on private members as well as public or package protected as well
If it doesn't match the names of the instance members, then it starts trying to match the getXXX and setXXX methods, if it doesn't match anything then it gives up.
With Annotations:
It uses the metadata supplied by the annotations to do the mapping and conversions.
It is always better to explicitly use the annotations when you have the source to add them to, then there is no guess work on what gets mapped to what.
Remember explicit is always better than implicit!
This is all well documented on the WIKI:
Mapping and Annotations
JSON Schema:
I am creating JSON Schema definitions for all my new projects now to document what is and isn't valid JSON according to the schema rules engine. It is a great way to document your data structures and eliminate parsing errors.

Categories