0

Javascript can't handle my longs, so I want RestEasy to wrap them with quotation marks to turn them into strings.

My DTO is :

public class DTO {
    Long id;
}

and I want this to be transferred as {"id":"2394872352498"}

Unfortunately, right now (by default) it is transferred as {"id":2394872352498} which is causing problems.

I'm using Jackson to serialize the data. Thanks for any help!

Riley Lark
  • 20,660
  • 15
  • 80
  • 128

1 Answers1

0

One solution I found:

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.SerializerProvider;
import org.codehaus.jackson.map.ser.std.SerializerBase;

public class LongToStringSerializer extends SerializerBase<Long>{


    public LongToStringSerializer(Class<?> t, boolean dummy) {
        super(t, dummy);
    }

    @Override
    public void serialize(Long arg0, JsonGenerator arg1, SerializerProvider arg2)
            throws IOException, JsonProcessingException {
        arg1.writeString(arg0 == null ? null : arg0.toString());
    }

}

Then, this serializer needs to be registered :

SimpleModule simpleModule = new SimpleModule("MyModule", new Version(0, 0, 0, null));
simpleModule.addSerializer(new LongToStringSerializer(Long.class, true));
objectMapper.registerModule(simpleModule);
Riley Lark
  • 20,660
  • 15
  • 80
  • 128