I want to serialize output from specific method (The name of method doesn't start with get
prefix).
class MyClass {
// private fields with getters & setters
public String customMethod() {
return "some specific output";
}
}
Example of JSON
{
"fields-from-getter-methods": "values",
"customMethod": "customMethod"
}
Output from customMethod()
is not serialized to JSON field. How can I achieve serialization of the output from customMethod()
without adding of get
prefix?
Use JsonProperty annotation in your method.
With Jackson2:
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();
}
}
}
Output:
{"name":"myName","customMethod":"test"}
Hope it helps!
Maybe this could be a solution?
@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY)
public class POJOWithFields {
private int value;
}
source: Changing property auto-detection
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