BeanIo嵌套列表修复了长度封送和取消封送



我不明白为什么嵌套对象没有从BeanIo中清楚地解析出来。

解析是基于";固定长度";,如此定位。

给这些pojos:

@Record(minOccurs=1) 
@Data
public class Address {

@Field(length=2)//,at=1)
private String prov;
@Field(length=6)//at=2)
private String city; 
}

@Record(minOccurs=1) 
@Data
public class Employee { 
@Field(length=6)//,at=1)
private String firstName; 
private List<Address> addresses; 
@Field(length=6)//at=2)
private String lastName; 
}

我制作了这个类来尝试输入和输出操作来澄清问题:

public class BeanioTest {
public static void main(String[] args) {
Employee emp = new Employee();
emp.setFirstName("Joe");
emp.setLastName("Black");
List<Address> addresses = new ArrayList<>();
Address address1 = new Address();
address1.setCity("PARIS");
addresses.add(address1);
Address address2 = new Address();
address2.setCity("MILAN");
addresses.add(address2);
emp.setAddresses(addresses);
String marshalled = marshaller(  emp);
System.out.println(marshalled);

Employee empUnm = unmarshaller(marshalled);
System.out.println(empUnm.toString());
} 
public static Employee unmarshaller(String emp) {
StreamFactory factory = StreamFactory.newInstance();
StreamBuilder builder = new StreamBuilder("s1")
.format("fixedlength") 
.addRecord(Employee.class)
.addRecord(Address.class);
factory.define(builder);
Unmarshaller unmarshaller = factory.createUnmarshaller("s1"); 
Employee unmarshalled = (Employee) unmarshaller.unmarshal(emp); 
return unmarshalled;     
}
public static String marshaller(Employee emp) {
StreamFactory factory = StreamFactory.newInstance();
StreamBuilder builder = new StreamBuilder("Tm")
.format("fixedlength") 
.addRecord(Employee.class)
.addRecord(Address.class);
factory.define(builder);
Marshaller marshaller = factory.createMarshaller("Tm"); 
String marshalled = marshaller.marshal(emp).toString(); 
return marshalled;   
}
}

但是输入和输出不会考虑嵌套集合,控制台输出如下所示:

Joe   Black 
Employee(firstName=Joe, addresses=null, lastName=Black)

我试过各种各样的尝试,但都搞不清楚。请给我指正确的方向。

请参阅BeanIO参考指南的"分段"部分。在这里复制太多了,但分段用于指示@Record中的嵌套对象。要使用线段,需要使用@Segment注释对属性List<Address>进行注释,并在这种情况下指定集合类型。然后您的Employee类变为:

@Data
@Record(minOccurs = 1)
@SuppressWarnings("javadoc")
public class Employee {
@Field(length = 6)// ,at=1)
private String firstName;
@Segment(collection = List.class)
private List<Address> addresses;
@Field(length = 6)// at=2)
private String lastName;
}

您可以为线束段配置各种其他属性。有关更多选项,请参阅文档。

附言:不是问题的一部分,但你的测试代码中可能有一个拼写错误:

Address address2 = new Address();
address1.setCity("MILAN"); // I assume you want MILAN to be the city for address2, not address1
addresses.add(address2);

相关内容

  • 没有找到相关文章

最新更新