Jor*_*.S. 11 java serialization json jackson
我有一个对象甲一些方法毫安,MB,MC和该对象实现了接口乙仅毫安和MB.
当我序列化B时,我期望只有ma和mb作为json响应,但我也得到了mc.
我想自动化这种行为,以便我序列化的所有类都基于接口而不是实现来序列化.
我该怎么办?
例:
public interface Interf {
public boolean isNo();
public int getCountI();
public long getLonGuis();
}
Run Code Online (Sandbox Code Playgroud)
执行:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
连载:
ObjectMapper mapper = new ObjectMapper();
Interf interf = new Impl();
String str = mapper.writeValueAsString(interf);
System.out.println(str);
Run Code Online (Sandbox Code Playgroud)
响应:
{
"patata": "Patata",
"count": 231321,
"yes": true,
"no": false,
"countI": 23,
"lonGuis": 4324523423423423500
}
Run Code Online (Sandbox Code Playgroud)
预期回复:
{
"no": false,
"countI": 23,
"lonGuis": 4324523423423423500
}
Run Code Online (Sandbox Code Playgroud)
bro*_*eib 14
只需注释您的界面,以便Jackson根据接口的类而不是底层对象的类构造数据字段.
@JsonSerialize(as=Interf.class)
public interface Interf {
public boolean isNo();
public int getCountI();
public long getLonGuis();
}
Run Code Online (Sandbox Code Playgroud)
您有两个选择:
1)@JsonSerialize在您的界面上添加注释(请参阅@broc.seib 答案)
2) 或使用特定的 writer 进行序列化(从 Jackson 2.9.6 开始):
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writerFor(Interf.class).writeValueAsString(interf);
Run Code Online (Sandbox Code Playgroud)