Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

json

jackson

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?

like image 789
misco Avatar asked May 05 '15 08:05

misco


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

}
}

Output:

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

Hope it helps!

like image 137
jbarrueta Avatar answered Sep 29 '22 02:09

jbarrueta


Maybe this could be a solution?

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

source: Changing property auto-detection

like image 42
Kuurde Avatar answered Sep 29 '22 01:09

Kuurde