Home > Software engineering >  How to serialize a java object into a string?
How to serialize a java object into a string?

Time:11-10

I am working on the migration of a legacy API to microservice. The legacy API is encoding a java object into a base64 String. The following code is used:

public String serialize() throws Exception {
    String mementoXml = null;
    Document document = DocumentHelper.createDocument();
    Element dictionary = document.addElement("Dictionary");
    dictionary.add(this.addChildren());
    StringWriter sw = new StringWriter();
    OutputFormat format = OutputFormat.createPrettyPrint();
    format.setIndent(" ");
    format.setTrimText(false);
    XMLWriter writer = new XMLWriter(sw, format);

    try {
        writer.write(document);
        writer.flush();
    }
    catch (Exception var8) {

    }
    mementoXml = sw.toString().replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
    return encodeString(mementoXml);
}

public Element addChildren(){
    Element response DocumentHelper.createElement("response");
    Element el1 = response.addElement("element");
    el1.setText(this.javaObject.getValue());
    return response;
}

The method for encoding is:

public String encodeString(String in) throws EncoderException {
    CompressedBase64Impl impl = new CompressedBase64Impl();
    String output = null;
    output = impl.encodeBytes(in.getBytes());
    return output;
}

What would be the modernized way in Spring boot to encode an object into a base64String. Is there something like JSONWriter?

CodePudding user response:

This writes to an ObjectOutputStream, which then writes to a Base64 encoding converter, which then writes to a byte array, which is then converted to a String.

public class EncodeToBase64 {
    public static void main(String[] args) throws Exception {
        List<?> someObjectToSerialize = new ArrayList<>();
        System.out.println( serializeToBase64( someObjectToSerialize ) );
    }

    private static String serializeToBase64( Object someObjectToSerialize ) throws IOException {
        try( final ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream objectOutputStream = new ObjectOutputStream( Base64.getEncoder().wrap( baos ) ) ) {
            objectOutputStream.writeObject( someObjectToSerialize );
            return baos.toString();
        }
    }
}

CodePudding user response:

String encodedString =  Base64.getEncoder().encodeToString(originalInput.getBytes());

This way you can convert to a base 64 encoded string. Base64 comes with java.util package.

  • Related