[英]mapping from flat protobuf message to class with inner classes using mapStruct
I need to use mapStruct
to write a mapping from message AddressProto
to the class
Address.我需要使用
mapStruct
编写从消息AddressProto
到class
地址的映射。 But message AddressProto
consists only of string fields while Address
class has inner classes.但是消息
AddressProto
仅包含字符串字段,而Address
类具有内部类。
I have written such a mapper so far, but due to the difference between the message structure and the class, I don't know how to correctly map fields from message AddressProto
to class Address
and back.到目前为止,我已经编写了这样一个映射器,但是由于消息结构和类之间的差异,我不知道如何正确地将字段从消息
AddressProto
映射到类Address
并返回。
@Mapper(config = MapstructConfig.class, unmappedTargetPolicy = ReportingPolicy.ERROR)
public abstract class AddressProtoMapper {
// from proto to object
public abstract Address mapToAddress(AddressProto address);
// from object to proto
public abstract AddressProto mapAddressToProto(Address address);
}
proto message AddressProto
(after the slash for each field, I wrote in which class field it needs to be mapped): proto 消息
AddressProto
(在每个字段的斜线之后,我写了它需要映射到哪个类字段):
message AddressProto {
string value = 1; // Address.AddressValue.value
string unrestricted_value = 2; // Address.AddressValue.unrestrictedValue
string country = 3; // Address.Structure.Country.name
string country_iso_code = 4; // Address.Structure.Country.isoCode
string region = 5; // Address.Structure.Region.name
}
java class Address
: java类
Address
:
public class Address {
public final AddressValue value;
public final Structure structure;
public static class AddressValue {
public final String value;
public final String unrestrictedValue;
}
public static class Structure {
public final Country country;
public final Region region;
public static class Country {
public final String name;
public final String isoCode;
}
public static class Region {
public final String name;
}
}
}
The solution turned out to be very simple.结果证明解决方案非常简单。 Even too much :) You just need to write your own implementation.
甚至太多 :) 您只需要编写自己的实现即可。
@Mapper(
config = MapstructConfig.class,
unmappedTargetPolicy = ReportingPolicy.ERROR
)
public interface AddressProtoMapper {
default Address mapToAddress(AddressProto address){
return new Address(
...
);
}
default AddressProto mapAddressToProto(Address address) {
return new AddressProto(
...
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.