Andrei
Andrei

Reputation: 53

Is it possible to serialize with Jackson additional properties?

I am trying to serialize a class with Jackson in such a way that for serialization my class sends a property in 2 different ways(as a String and an enum). How do i determine Jackson to actually add a different property to the JSON output without declaring it?

My code is

private LearningForm cnfpLearningOrganisationLearningForm;
......
/**
 * @return the cnfpLearningOrganisationLearningForm
 */
public String getCnfpLearningOrganisationLearningFormSearch() {
    return cnfpLearningOrganisationLearningForm.getValue();
}

/**
 * @return the cnfpLearningOrganisationLearningForm
 */
public LearningForm getCnfpLearningOrganisationLearningForm() {
    return cnfpLearningOrganisationLearningForm;
}

I want Jackson to serialize this as: { .... cnfpLearningOrganisationLearningForm : someValue cnfpLearningOrganisationLearningFormSearch : differentValue .... }

Is there a way to do this without declaring cnfpLearningOrganisationLearningFormSearch as a (useless except for serialization) field in the class?

Thank you.

Upvotes: 1

Views: 2092

Answers (3)

Programmer Bruce
Programmer Bruce

Reputation: 66973

Is there a way to do this without declaring cnfpLearningOrganisationLearningFormSearch as a (useless except for serialization) field in the class?

Yes. By default, Jackson will use getters as properties, without consideration for any fields. So, the bean described in the original question should serialize as wanted, just fine.

The following code demonstrates this point (with an unnecessary enum thrown in for good measure).

import com.fasterxml.jackson.databind.ObjectMapper;

public class JacksonFoo
{
  public static void main(String[] args) throws Exception
  {
    System.out.println(new ObjectMapper().writeValueAsString(new Bar()));
    // output: {"propertyAsValue":"some_value","propertyAsEnum":"VALUE"}
  }
}

class Bar
{
  public String getPropertyAsValue()
  {
    return MyEnum.VALUE.getValue();
  }

  public MyEnum getPropertyAsEnum()
  {
    return MyEnum.VALUE;
  }
}

enum MyEnum
{
  VALUE;

  public String getValue()
  {
    return "some_value";
  }
}

Upvotes: 0

bvulaj
bvulaj

Reputation: 5133

If I'm understanding the question correctly, you can solve this with mixins. Especially since it sounds like you may not be able to modify the entity.

Upvotes: 1

Boris Treukhov
Boris Treukhov

Reputation: 17774

There is @JsonProperty annotation, which allows you to dynamically evaluate the property value(you can declare it to return Object if you want to return both enumerations and strings, if I understood the question correctly)

@JsonProperty("test")
public Object someProp(){
    if (condition) return SomeEnum.VALUE;
    else
        return "StringValue";
}

Upvotes: 0

Related Questions