0

I'm working in an organization where we want to convert an object to string representation and then encode it using Base64.Encoder in Java. But the problem is, the object which we are receiving from other systems doesn't implement the Serializable interface.

If it doesn't implement Serializable interface, then how can we convert the object to a string representation irrespective of the type of object ?

Sugyan sahu
  • 129
  • 1
  • 8
  • `Serializable` is used to convert an object to a `byte[]`, not a `String`, so your whole approach sounds wrong. – Kayaman Dec 29 '19 at 12:34
  • The ultimate goal is to convert the object to string, then byte[ ] and then encode it using Base64. Base64 only accepts in byte array, I suppose. – Sugyan sahu Dec 29 '19 at 12:37
  • `DatatypeConverter.printBase64Binary(object.toString().getBytes())` This depends on your implementation of toString() – Sagar Ahuja Dec 29 '19 at 12:56

3 Answers3

1

You have to to it 'manually'.

If the object to serialize is a simple java bean (simple members, getters, setters) I would use a JSON serializer.

If it is more complex you have to implement a serialize/deserialize method yourself.

JSON's serialized format is already in text form, so you do not need to convert it to Base64. Base64 is intended to be used to convert binary content into readable/transferrable string respresentation.

Simple Example with Jackson:

        JarEntry obj = new JarEntry("Hello World"); 
        ObjectMapper objectMapper = new ObjectMapper(); 
        String json = objectMapper.writeValueAsString(obj);
        System.out.println(json);
Heri
  • 4,368
  • 1
  • 31
  • 51
  • thanks. But I'm surprised but the object is a complex one. What do you mean by "JSON's serialized format is already in text form" ? Does that mean, no need for the class to implement Serializable ? – Sugyan sahu Dec 29 '19 at 12:26
  • 1
    No, 'serialized' in common means that the content of something can be seen as continguous byte array which can be sent through a line or saved to disk as file. A java object in memory is represented by addresses, each member of the class may located elsewhere in the memory which is not per se serialized. – Heri Dec 29 '19 at 12:35
  • JSON serializers (e.g. Jackson) can deal with quite complex classes. Maybe this link helps you unterstand it better: https://stackoverflow.com/questions/3316762/what-is-deserialize-and-serialize-in-json – Heri Dec 29 '19 at 12:37
  • I suppose, the Jackson also needs to have a class to implement Serializable. I have tried the below. `SomeClass obj = new SomeClass (); ObjectMapper objectMapper = new ObjectMapper(); byte[] byteArr= objectMapper.writeValueAsBytes(obj);` This code throws "NotSerializableException" as the SomeClass is not implementing Serializable. – Sugyan sahu Dec 29 '19 at 12:39
  • I added a simple jackson example in my answer. The JarEntry is not Serializable, but jackson converts it to a JSON string. Try it with your own class. – Heri Dec 29 '19 at 13:29
  • Yeah!, Got it. Thanks. :) – Sugyan sahu Dec 29 '19 at 13:58
1

You can encode and decode to and from base64 using ObjectMapper and DatatypeConverter specially for your use case where your class does not implements Serializable.

public static String encode(AccessClient object) throws IOException{
    ObjectMapper mapper = new ObjectMapper();
    return DatatypeConverter.printBase64Binary(mapper.writeValueAsBytes(object));
}


public static AccessClient decode(String base64) throws IOException{
    byte [] bytes =  DatatypeConverter.parseBase64Binary(base64);
    ObjectMapper mapper = new ObjectMapper();
    return mapper.readValue(bytes,AccessClient.class);
}

Test Results :

public static void main(String [] args) throws IOException {
    AccessClient accessClient = new AccessClient();
    accessClient.setId("id");
    accessClient.setClientId(new BigInteger("200000"));
    accessClient.setClientName("clientName");
    String base64 = encode(accessClient);
    System.out.println(base64);
    System.out.println(decode(base64).toString());
}

-----------------------Output-------------------------- eyJpZCI6ImlkIiwiY2xpZW50SWQiOjIwMDAwMCwiY2xpZW50TmFtZSI6ImNsaWVudE5hbWUiLCJjbGllbnRBdHRyaWJ1dGVzIjpudWxsfQ==

AccessClient{id='id', clientId=200000, clientName='clientName', clientAttributes=null}

Sagar Ahuja
  • 637
  • 10
  • 10
1

Since I could not find tags for or so, here is my alternative:

Gson gson = new Gson();
NonSerializable ns = new NonSerializable(); // not implementing Serializable
// encode
byte[] b64 = Base64.getEncoder().encode(gson.toJson(ns).getBytes()); 
// decode
NonSerializable decoded = gson.fromJson(new String (Base64.getDecoder().decode(b64)),
        NonSerializable.class);

See also: Java serialization to string

pirho
  • 11,565
  • 12
  • 43
  • 70