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}"