开发者

Java SOJO CSV Serialization

开发者 https://www.devze.com 2023-02-08 08:00 出处:网络
I am trying to use SOJO to serialize a Java object to CSV. The example looks pretty straight forward:

I am trying to use SOJO to serialize a Java object to CSV. The example looks pretty straight forward:

Car car = new Car("My Car");
car.setDescription("This is my car.");
Serializer csvSerializer = new CsvSerializer();
String csvStr = (String) csvSerializer.serialize(car);
System.out.println(csvStr);
// print:
// description,build,properties,name,~unique-id~,class  
// This is my car.,,,My Car,0,test.net.sf.sojo.model.Car

I tried implementing my own version of the example. I made a really simple Car class with two String fields (build and description) which implements a setDescription(..) method.

This is what I implemented:

import net.sf.sojo.interchange.csv.CsvSerializer;


public class Main {

private class Car
{
    private String build;
    private String description;
    public Car(String build) {
        this.build = build;
        this.description = null;
    }

    public void setDescription(String description) {
        this.description = description;
    }


}

public static void main(String[] args) {
    Main m = new Main();
    Car car = m.new Car("My Car");
    car.setDescription("This is my car.");
    CsvSerializer csvSerializer = new CsvSerializer();
    String csvStr = (String) csvSerializer.serialize(car);
    System.out.println(csvStr);
}

}

However, when I run my implementation I get the following output:

~unique-id~,class,description
0,Main$Car,

I don't understand why in my implementation neither the build or description fields are serialized, can you help?

Ch开发者_开发知识库eers,

Pete


From the SOJO home page: "The intention for this project is a Java framework, that convert JavaBeans in a simplified representation"

The Car object in your example does not qualify. You must have a getter (and, probabaly, a setter as well) for every property that you wish SOJO to write to (or read from) your file. Add getBuild() and getDescription()


I haven't used SOJO, but for private fields you probably need getter methods; or you could try declaring the fields public.

0

精彩评论

暂无评论...
验证码 换一张
取 消