我想序列化特定方法的输出(方法名称不以get前缀开头)。
class MyClass {
// private fields with getters & setters
public String customMethod() {
return "some specific output";
}
}
Run Code Online (Sandbox Code Playgroud)
JSON 示例
{
"fields-from-getter-methods": "values",
"customMethod": "customMethod"
}
Run Code Online (Sandbox Code Playgroud)
输出customMethod()未序列化为 JSON 字段。如何在customMethod() 不添加 get 前缀的情况下实现输出的序列化?
在您的方法中使用 JsonProperty 注释。
与杰克逊2:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MyClass {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonProperty("customMethod")
public String customMethod() {
return "test";
}
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
MyClass test = new MyClass();
test.setName("myName");
try {
System.out.println(objectMapper.writeValueAsString(test));
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
{"name":"myName","customMethod":"test"}
希望能帮助到你!