Hi. I had similar wish: to implement simple exchange in Java objects skipping JSON intermediate layer.
Earlier there was a library Flavour-JSON which served for this. But it was error-prone and eventually its support was dropped together with Flavour.
This forced me to write my own converters from and to JSON objects.
On server side parser-reader is Jackson, on client side it is my library.
Here is its source code:
It supports records and works more-less as Jackson ObjectMapper without annotations.
To make object transferrable, you should inherit it from ua.ihromant.teavm.io.Message (later I will show how I'm doing this).
Still, as mentioned above, you don't know what information are you deserializing. So, I'm transferring class information using the following trick:
public interface ChatMessage extends Message {
ChatType getMt();
}
public enum ChatType {
CONNECT_MESSAGE(IdentityMessage.class)// and other messages
private final Class<? extends Message> cls; // and getter
}
public record IdentityMessage(String user, String tab) implements ChatMessage {
@Override
public ChatType getMt() {
return ChatType.IDENTITY_MESSAGE;
}
}
Then when you receive serialized message, you will have something like (if you are using Jacksons .enable(SerializationFeature.WRITE_ENUMS_USING_INDEX) to serialize enums as integers) :
{"user":"abc","tab":"def","mt":0}
Using this info you just read a message in the following way:
JSMapLike<JSObject> jso = JSON.parse(data);
Class<?> cls = ChatType.values()[jso.get("mt").<JSNumber>cast().intValue()].getCls();
return Converters.jsToJava(jso, cls);
Using Similarly you can serialize Java records etc in client side and send it to server side.
private JSObject convert(Object o) {
if (!(o instanceof ChatMessage m)) {
throw new IllegalArgumentException();
}
JSMapLike<JSObject> result = Converters.javaToJs(m).cast();
result.set("mt", JSNumber.valueOf(m.getMt().ordinal()));
return result;
}
public String write(Object o) {
return JSON.stringify(convert(o));
}
This implementation is simple and straightforward and I'm happily using it for 2+ years.