son*_*oom 37 java json jackson
我有一个User类,我想使用Jackson映射到JSON.
public class User {
private String name;
private int age;
prviate int securityCode;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
我使用 - 将其映射到JSON字符串 -
User user = getUserFromDatabase();
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
Run Code Online (Sandbox Code Playgroud)
我不想映射securityCode
变量.有没有办法配置映射器以便忽略该字段?
我知道我可以编写自定义数据映射器或使用Streaming API但我想知道是否可以通过配置来完成它?
Rav*_*har 62
您有两种选择:
杰克逊在场地的安排者身上工作.因此,您可以删除要在JSON中省略的字段的getter.(如果你不需要在其他地方使用吸气剂.)
或者,您可以在该字段的getter方法中使用@JsonIgnore
Jackson的注释,并且您在结果JSON中看到没有这样的键值对.
@JsonIgnore
public int getSecurityCode(){
return securityCode;
}
Run Code Online (Sandbox Code Playgroud)Ben*_*tes 12
您还可以收集注释类的所有属性
@JsonIgnoreProperties( { "applications" })
public MyClass ...
String applications;
Run Code Online (Sandbox Code Playgroud)
so-*_*ude 12
在这里添加这个是因为其他人可能会在将来再次搜索这个,就像我一样.本答案是对接受的答案的延伸
You have two options:
1. Jackson works on setters-getters of fields. So, you can just remove getter of field which you want to omit in JSON. ( If you don't need getter at other place.)
2. Or, you can use the `@JsonIgnore` [annotation of Jackson][1] on getter method of that field and you see there in no such key-value pair in resulted JSON.
@JsonIgnore
public int getSecurityCode(){
return securityCode;
}
Run Code Online (Sandbox Code Playgroud)
实际上,较新版本的Jackson为JsonProperty添加了READ_ONLY和WRITE_ONLY注释参数.所以你也可以这样做.
@JsonProperty(access = Access.WRITE_ONLY)
private String securityCode;
Run Code Online (Sandbox Code Playgroud)
代替
@JsonIgnore
public int getSecurityCode(){
return securityCode;
}
Run Code Online (Sandbox Code Playgroud)
如果您不想在Pojos上添加注释,您也可以使用Genson.
以下是如何在没有任何注释的情况下使用它排除字段(如果需要,也可以使用注释,但您可以选择).
Genson genson = new Genson.Builder().exclude("securityCode", User.class).create();
// and then
String json = genson.serialize(user);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
66979 次 |
最近记录: |