JRun
JRun

Reputation: 3428

Is it possible to create overloaded setters for Jackson/POJO mapper?

I have a class:

    @Column(name = "data", nullable = false)
String  data;


public void setData(final String data) {
    this.data = data;
}


public void setDataAsSet(final Set<String> strings) {
    setData(JOINER.join(strings));
}

Can Jackson serialize / de-serialize it? Ideally I would like to (at least) support de-serialization.

I've searched the web and found no clear answer. Some bug reports, and suggestions to @ignore the 'un-necessary' getter / setter, but I want all of them.

Thanks.

Upvotes: 1

Views: 1123

Answers (1)

Opal
Opal

Reputation: 84784

It seems to be possible with writing custom deserializer. Unfortunately have no opportunity to set the env now and try. But in general I don't it's a good idea to send same data as String or Set<String>. It will result in hard to debug bugs or other unpredictable problems. There should be two separately declared fields or it should always be a collection (in most cases it will probably have single element). Rethink it please.

I still encourage You to rethink the design nevertheless did it:

Bean:

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

public class SampleBean {

    @JsonDeserialize(using = SampleDeserializer.class)
    public String data;
}

Deserializer:

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

import java.io.IOException;
import java.util.List;

import static com.fasterxml.jackson.core.JsonToken.VALUE_STRING;

public class SampleDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctx) throws IOException {
        JsonToken jt = jp.getCurrentToken();
        if (jt == VALUE_STRING) {
            return jp.getValueAsString();
        } else if (jt == JsonToken.START_ARRAY) {
            return jp.readValueAs(List.class).toString().replace("[", "").replace("]", "").replaceAll("\\s*", "");// joining could be done much better of course
        }

        return null;
    }
}

Test:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Assert;
import org.junit.Test;

import java.io.IOException;

public class SampleTest {

    @Test
    public void test() throws IOException {
        final String json = "{\"data\":\"2\"}";
        final String json2 = "{\"data\":[\"2\",\"3\"]}";

        ObjectMapper om = new ObjectMapper();
        SampleBean sb = om.readValue(json, SampleBean.class);
        Assert.assertEquals("2", sb.data);
        sb = om.readValue(json2, SampleBean.class);
        Assert.assertEquals("2,3", sb.data);
    }
}

Upvotes: 1

Related Questions