I'm trying to serialise an object with a Long id to JSON, using Genson.
It works well if I serialise to JSON and back into Java. But I'm deserialising in JavaScript.
JavaScript can't support a full 64-bit unsigned int as a Number (I'm finding the last few bits of my id are being zeroed in JavaScript), so I need to convert the Long id to a String during serialisation.
I don't want to convert all the Longs in the Object, so I'm trying to use a Converter for just the id field.
import com.owlike.genson.annotation.JsonConverter;
import javax.persistence.Id;
import lombok.Getter;
import lombok.Setter;
...
/** the local database ID for this order */
@JsonConverter(LongToStringConverter.class)
@Id
@Setter
@Getter
private Long id;
/** The unique ID provided by the client */
@Setter
@Getter
private Long clientKey;
My converter code looks like this:
public class LongToStringConverter implements Converter<Long> {
/** Default no-arg constructor required by Genson */
public LongToStringConverter() {
}
@Override
public Long deserialize(ObjectReader reader, Context ctx) {
return reader.valueAsLong();
}
@Override
public void serialize(Long obj, ObjectWriter writer, Context ctx) {
if (obj != null) {
writer.writeString(obj.toString());
}
}
}
I'm not doing anything special when invoking serialisation itself:
Genson genson = new GensonBuilder().useIndentation(true).create();
String json = genson.serialize( order );
This doesn't work. Output still looks like this:
{
"clientKey":9923001278,
"id":1040012110000000002
}
What I'm trying to achieve is this:
{
"clientKey":9923001278,
"id":"1040012110000000002" // value is quoted
}
I did also try to pass my Converter into a GensonBuilder but that hits all the Longs in the object, which isn't what I need.
Any advice?