I have one object A with some methods ma, mb, mc and this object implements an interface B with only ma and mb.
When I serialize B I expect only ma and mb as a json response but I get as well mc.
I'd like to automatize this behaviour so that all the classes I serialize get serialized based on the interface and not on the implementation.
How should I do that?
Example:
public interface Interf {
public boolean isNo();
public int getCountI();
public long getLonGuis();
}
Implementation:
public class Impl implements Interf {
private final String patata = "Patata";
private final Integer count = 231321;
private final Boolean yes = true;
private final boolean no = false;
private final int countI = 23;
private final long lonGuis = 4324523423423423432L;
public String getPatata() {
return patata;
}
public Integer getCount() {
return count;
}
public Boolean getYes() {
return yes;
}
public boolean isNo() {
return no;
}
public int getCountI() {
return countI;
}
public long getLonGuis() {
return lonGuis;
}
}
Serialization:
ObjectMapper mapper = new ObjectMapper();
Interf interf = new Impl();
String str = mapper.writeValueAsString(interf);
System.out.println(str);
Response:
{
"patata": "Patata",
"count": 231321,
"yes": true,
"no": false,
"countI": 23,
"lonGuis": 4324523423423423500
}
Expected response:
{
"no": false,
"countI": 23,
"lonGuis": 4324523423423423500
}
Jackson can serialize and deserialize polymorphic data structures very easily. The CarTransporter can itself carry another CarTransporter as a vehicle: that's where the tree structure is! Now, you know how to configure Jackson to serialize and deserialize objects being represented by their interface.
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
Advertisements. let's serialize a java object to a json file and then read that json file to get the object back. In this example, we've created Student class.
Just annotate your interface such that Jackson constructs data fields according to the interface's class and not the underlying object's class.
@JsonSerialize(as=Interf.class)
public interface Interf {
public boolean isNo();
public int getCountI();
public long getLonGuis();
}
You have two options:
1) put @JsonSerialize
annotation on your interface (see @broc.seib answer)
2) or use specific writer for the serialization (as of Jackson 2.9.6):
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writerFor(Interf.class).writeValueAsString(interf);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With