I have the list of instances of a class which kind of complicated: it have many val's including nested classes those also have many val's. I want to write in a file in either json
or xml
format.
I found a simple example which seems to do what I want (in Java, though, but it really doesn't matter):
#Main.java
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Main {
public static void main(String args[]) {
try {
Employee employee = new Employee("0001", "Robert", "Newyork City", "IT");
FileOutputStream fos = new FileOutputStream("my-data.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(employee);
oos.flush();
oos.close();
System.out.println("Employee Object written to file employee.dat");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
#Employee.java
import java.io.Serializable;
public class Employee implements Serializable {
private String empId;
private String Name;
private String Address;
private String Dept;
public Employee(String empId, String name, String address, String dept) {
this.empId = empId;
this.Name = name;
this.Address = address;
this.Dept = dept;
}
public String toString() {
return "[Employee: " + empId + ", " + ", " + Name + ", " + Address + ", " + Dept + "]";
}
}
And what I had as an output was a binary data written in a file. Moreover, toString()
methods enumerates all fields manually, which is unacceptable for my real class.
So how do I do that? I'd really appreciate if you give even a small example of it, instead of saying "there is a library called X, use it". I've already failed using all these libraries in my previous question about serialization. I'm not sure yet if what I need is serialization, because I need it to be stored in not binary, but in xml or json format.