0

Goal: Create a JSON string for a Java object.(Previously I have a .NET solution for this using ISerializable -> GetObjectData).

As I am very new to JAVA, I have a doubt in how to write a Serializable class.

Created a serializable class and tried to write it as JSON by customizing writeObject but in the output string I am getting a few unwanted ASCII characters.

public class Employee implements Serializable  {
    private static final long serialVersionUID = 1L;
    private String serializeValueName;
    private int nonSerializeValueSalary;

    public String getSerializeValueName() {
        return serializeValueName;
    }

    public void setSerializeValueName(String serializeValueName) {
        this.serializeValueName = serializeValueName;
    }

    public int getNonSerializeValueSalary() {
        return nonSerializeValueSalary;
    }

    public void setNonSerializeValueSalary(int nonSerializeValueSalary) {
        this.nonSerializeValueSalary = nonSerializeValueSalary;
    }

    @Override
    public String toString() {
        return "Employee [serializeValueName=" + serializeValueName + "]";
    }

    private void writeObject(ObjectOutputStream oos) throws IOException {       
        oos.writeObject(String.format("{\"ValueName\":\"%s\",\"ValueSalary\":%s}", getSerializeValueName(), getNonSerializeValueSalary()));
    }

    public String serialize() {
        String serializedObject = "";
         try {
             ByteArrayOutputStream bo = new ByteArrayOutputStream();
             ObjectOutputStream so = new ObjectOutputStream(bo);
             writeObject(so);
             so.flush();
             serializedObject = bo.toString().substring(7);
         } catch (Exception e) {
             System.out.println(e);
         }      
        return serializedObject;        
    }
}

    public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
        Employee employeeOutput = null;
        FileOutputStream fos = null;
        ObjectOutputStream oos = null;
        employeeOutput = new Employee();
        employeeOutput.setSerializeValueName("Aman");
        employeeOutput.setNonSerializeValueSalary(50000);
        String test = employeeOutput.serialize();
    }

Current output is prefixed with ’ so added substring method to clip the characters at the start.

Expected output : "{"ValueName":"Aman","ValueSalary":50000}"

Kesavan D
  • 184
  • 5
  • take a look into GSON – Tschallacka Jan 20 '20 at 10:07
  • ObjectOutputStream does not output JSON. It serializes to using the Java object serialization protocol / format. See the linked Q&A for ways to serialize POJOs as JSON. – Stephen C Jan 20 '20 at 10:11
  • (If you want to serialize to JSON by hand, you could create the string as you are doing. But you you should then just return the string rather than shoving it through an ObjectOutputStream. The last step doesn't achieve anything.) – Stephen C Jan 20 '20 at 10:15

0 Answers0