1

I am getting an instance of Serializable out of some internal APIs. The Serializable instance is actually Long or String, etc. Is there a way to make a DTO that can handle this situation? Using private Serializable value; the JSON ends up with value: {}.

UPDATE

Here is a reduced example of the code in question:

@Controller
public class SomeController
{
  //...
  public MyDto getInfo(Long id)
  {
    MyDto result = new MyDto();
    Serializable obj = svc.getInfo(id);
    // obj is either Long, or String, or one of few more fundamental Java types
    result.setValue(obj);
    return result;
  }
}

public class MyDto
{
  private Serializable value;
  public void setValue(Serializable info)
  {
    this.value = value;
  }
  public Serializable getValue()
  {
    return value;
  }
}

UPDATE 2

I have found the answer to my problem here: https://stackoverflow.com/a/20494813/341065

Community
  • 1
  • 1
wilx
  • 17,697
  • 6
  • 59
  • 114

1 Answers1

8

Note that Jackson does not use java.io.Serializable for anything: there is no real value for adding that. It gets ignored.

Given this, Jackson will see values as equivalent of whatever actual type is (for serialization, i.e. writing JSON); or, when reading, as equivalent of java.lang.Object.

If you know the actual type, you could annotate property with @JsonDeserialize(as=ActualType.class) to give a hint. But if actual values are Strings and Longs, this really should not be needed.

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • The actual type is one of few Java types like `Long` or `String`. The internal API returns `Serializable`. I have tried passing just `private Object value;` in the DTO but I get nothing in the JSON. – wilx Feb 07 '14 at 20:37
  • 1
    Jackson definitely should serialize Long as basic JSON number, String as JSON String. But do you return these values as-is, or in a wrapper Object of some kind? – StaxMan Feb 09 '14 at 03:06