How to serialize output from user method to JSON using Jackson?

I want to serialize the output from a specific method (the method name does not start with a prefix get).

class MyClass {
    // private fields with getters & setters

    public String customMethod() {
        return "some specific output";
    }
}

JSON example

{
    "fields-from-getter-methods": "values",
    "customMethod": "customMethod"
}

Exit is customMethod()not serialized in the JSON field. How to serialize output from customMethod() without adding a get prefix ?

+4
source share
3 answers

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();
    }

}
}

Conclusion:

{"name":"myName","customMethod":"test"}

Hope this helps!

+3
source

This should help. @JsonProperty ("customMethod")

+1
source

, ?

@JsonAutoDetect(fieldVisibility=JsonAutoDetect.Visibility.ANY)
public class POJOWithFields {
  private int value;
}

source:

+1

All Articles