Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package org.example;
- import com.fasterxml.jackson.annotation.*;
- import com.fasterxml.jackson.core.JsonGenerator;
- import com.fasterxml.jackson.core.JsonToken;
- import com.fasterxml.jackson.core.type.WritableTypeId;
- import com.fasterxml.jackson.databind.*;
- import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
- import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
- import com.fasterxml.jackson.dataformat.xml.XmlMapper;
- import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
- import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
- import org.example.TextMessage;
- import java.io.IOException;
- import java.io.Serializable;
- public class Main {
- public static void main(String[] args) throws IOException {
- XmlMapper xmlMapper = new XmlMapper();
- xmlMapper.setSerializerFactory(xmlMapper.getSerializerFactory()
- .withSerializerModifier(new ServerMessageSerializerModifier()));
- ServerMessage.LoginResponse loginResponse = new ServerMessage.LoginResponse(12345);
- String serializedLoginResponse = xmlMapper.writeValueAsString(loginResponse);
- System.out.println("Serialized LoginResponse: " + serializedLoginResponse);
- }
- }
- @JacksonXmlRootElement(localName = "ServerMessage")
- @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
- @JsonSubTypes({
- @JsonSubTypes.Type(value = ServerMessage.LoginResponse.class, name = "login_response"),
- @JsonSubTypes.Type(value = ServerMessage.NewMessage.class, name = "new_message")
- })
- abstract class ServerMessage implements Serializable {
- public enum ErrorType {
- ERROR, SUCCESS
- }
- @JsonIgnore
- @JacksonXmlProperty(isAttribute = false)
- private final ErrorType errorType;
- @JsonCreator
- protected ServerMessage(@JsonProperty("errorType") ErrorType errorType) {
- this.errorType = errorType != null ? errorType : ErrorType.SUCCESS;
- }
- @JsonIgnore
- public ErrorType getErrorType() {
- return errorType;
- }
- public static final class LoginResponse extends ServerMessage {
- private final int sessionID;
- public LoginResponse(int sessionId) {
- super(ErrorType.SUCCESS);
- this.sessionID = sessionId;
- }
- @JsonCreator(mode = JsonCreator.Mode.DISABLED)
- public LoginResponse() {
- super(ErrorType.SUCCESS);
- this.sessionID = 0; // or any default value you prefer
- }
- @JsonProperty("sessionID")
- @JacksonXmlProperty(localName = "sessionID")
- public int getSessionID() {
- return sessionID;
- }
- }
- public static final class NewMessage extends ServerMessage {
- private TextMessage message;
- public NewMessage() {
- super(ErrorType.SUCCESS);
- }
- public NewMessage(TextMessage message) {
- super(ErrorType.SUCCESS);
- this.message = message;
- }
- @JsonProperty("message")
- @JacksonXmlProperty(localName = "message")
- public TextMessage getMessage() {
- return message;
- }
- }
- public static String serialize(ServerMessage message) throws IOException {
- XmlMapper xmlMapper = new XmlMapper();
- return xmlMapper.writer().withRootName(message.getErrorType().name()).writeValueAsString(message);
- }
- public static ServerMessage deserialize(String xml) throws IOException {
- XmlMapper xmlMapper = new XmlMapper();
- xmlMapper.registerSubtypes(LoginResponse.class, NewMessage.class);
- xmlMapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
- return xmlMapper.readValue(xml, ServerMessage.class);
- }
- }
- class ServerMessageSerializerModifier extends BeanSerializerModifier {
- @Override
- public JsonSerializer<?> modifySerializer(
- SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
- if (ServerMessage.class.isAssignableFrom(beanDesc.getBeanClass())) {
- return new ServerMessageSerializer((JsonSerializer<Object>) serializer);
- }
- return serializer;
- }
- }
- class ServerMessageSerializer extends JsonSerializer<Object> {
- private final JsonSerializer<Object> defaultSerializer;
- ServerMessageSerializer(JsonSerializer<Object> defaultSerializer) {
- this.defaultSerializer = defaultSerializer;
- }
- @Override
- public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
- if (value instanceof ServerMessage serverMessage) {
- gen.writeStartObject();
- gen.writeObjectField("errorType", serverMessage.getErrorType());
- gen.writeFieldName(gen.getOutputContext().getCurrentName()); // Write the field name
- gen.writeStartObject(); // Start the object for the current field
- defaultSerializer.unwrappingSerializer(null).serialize(value, gen, serializers);
- gen.writeEndObject(); // End the object for the current field
- gen.writeEndObject();
- } else {
- defaultSerializer.serialize(value, gen, serializers);
- }
- }
- @Override
- public void serializeWithType(
- Object value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException {
- // Include type id handling
- WritableTypeId typeId = typeSer.typeId(value, JsonToken.START_OBJECT);
- typeSer.writeTypePrefix(gen, typeId);
- serialize(value, gen, serializers);
- typeSer.writeTypeSuffix(gen, typeId);
- }
- }
- Exception in thread "main" com.fasterxml.jackson.core.JsonGenerationException: Can not start an object, expecting field name
- at com.fasterxml.jackson.core.JsonGenerator._reportError(JsonGenerator.java:2849)
- at com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator._verifyValueWrite(ToXmlGenerator.java:1297)
- at com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator.writeStartObject(ToXmlGenerator.java:563)
- at org.example.ServerMessageSerializer.serialize(Main.java:129)
- at org.example.ServerMessageSerializer.serializeWithType(Main.java:147)
- at com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:32)
- at com.fasterxml.jackson.dataformat.xml.ser.XmlSerializerProvider.serializeValue(XmlSerializerProvider.java:108)
- at com.fasterxml.jackson.databind.ObjectMapper._writeValueAndClose(ObjectMapper.java:4719)
- at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3964)
- at org.example.Main.main(Main.java:25)
Advertisement
Add Comment
Please, Sign In to add comment