I am developing and spring application and for object mapping I am using ModelMapper library.
I am able to map basic class mapping but when I am trying to map 2 collection elements, source is set of enumeration with additional property like name and description and destination is pojo having id, name and description.
I have tried typemap and converters in mapping profile but I am getting exception of mapper.
And the source class is from other application(whose dependency have been added in pom.xml). I also don't want source type as an argument in setter of destination.
Ex.
SOURCE:
public class VType{
private int id;
private String name;
private String description;
}
public class VDTO{
private Set<VType> vTypes;
public Set<VType> getVTypes(){
return this.vTypes;
}
public void setVType() { //here I don't want to pass source type as an argument
//code stuff that I don't know what to do here
}
}
SOURCE ENUM:
public enum SourceVType{
V1(1, "Name1", "Desc1");
V2(2, "Name2", "Desc2");
private Integer id;
private String name;
private String description;
SourceVType(Integer id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
//getter-setter
}
Have you tried converter feature of modelmapper. You can use typemap converter to achieve this requirement.
#RunWith(JUnit4.class)
public class TempTest {
#Test
public void TestThis(){
final ModelMapper mapper = new ModelMapper();
mapper.addMappings(new PropertyMap<SrcClass, DestClass>() {
#Override
protected void configure() {
this.map().setId(this.source.getId());
this.map().setName(this.source.getName());
mapper.createTypeMap(TypeEnum.class, TypeClass.class).setConverter(
new Converter<TypeEnum, TypeClass>() {
#Override
public TypeClass convert(MappingContext<TypeEnum, TypeClass> mappingContext) {
if (mappingContext.getSource() == null) {
return null;
}
TypeEnum typeEnum = mappingContext.getSource();
TypeClass typeClass = new TypeClass();
typeClass.setId(typeEnum.getId());
typeClass.setName(typeEnum.getName());
return typeClass;
}
});
}
});
SrcClass srcObj = new SrcClass();
srcObj.setId(1);
srcObj.setName("name");
srcObj.setTypes(new HashSet<>(Arrays.asList(TypeEnum.TYPE1, TypeEnum.TYPE2)));
DestClass dstObj = mapper.map(srcObj, DestClass.class);
Assert.assertEquals(srcObj.getId(), dstObj.getId());
Assert.assertEquals(srcObj.getName(), dstObj.getName());
Assert.assertEquals(srcObj.getTypes().size(), dstObj.getTypes().size());
for(TypeClass c : dstObj.getTypes()) {
TypeEnum e = TypeEnum.getById(c.getId());
Assert.assertNotNull(e);
Assert.assertTrue(srcObj.getTypes().contains(e));
}
}
public static <Source, Result> Set<Result> convertAll(Set<Source> source, Function<Source, Result> projection)
{
Set<Result> results = new HashSet<>();
if(source == null) return results;
for (Source element : source)
{
results.add(projection.apply(element));
}
return results;
}
public static class SrcClass{
private Integer id;
private String name;
private Set<TypeEnum> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeEnum> getTypes() {
return types;
}
public void setTypes(Set<TypeEnum> types) {
this.types = types;
}
}
public static class DestClass{
private Integer id;
private String name;
private Set<TypeClass> types;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<TypeClass> getTypes() {
return types;
}
public void setTypes(Set<TypeClass> types) {
this.types = types;
}
}
public static enum TypeEnum{
TYPE1(1, "Type 1")
, TYPE2(2, "Type 2")
, TYPE3(3, "Type 3")
, TYPE4(4, "Type 4");
private Integer id;
private String name;
TypeEnum(Integer id, String name) {
this.id = id;
this.name = name;
}
private static final Map<Integer, TypeEnum> byId = new HashMap<>();
private static final Map<String, TypeEnum> byName = new HashMap<>();
static {
for (TypeEnum e : TypeEnum.values()) {
if (byId.put(e.getId(), e) != null) {
throw new IllegalArgumentException("duplicate id: " + e.getId());
}
if (byName.put(e.getName(), e) != null) {
throw new IllegalArgumentException("duplicate name: " + e.getName());
}
}
}
public Integer getId() {
return this.id;
}
public String getName() { return this.name; }
public static TypeEnum getById(Integer id) {
return byId.get(id);
}
public static TypeEnum getByName(String name) {
return byName.get(name);
}
}
public static class TypeClass{
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I want to create bean in java corresponding to below json
{
"name": "",
"id": "",
"dept": {
"deptId": "",
"deptName": "",
"course": {
"courseId": "",
}
}
}
My idea is to create parent class and keep dept and course as inner private classes and then have getters setters to get or set data and form parent bean. But I am getting error "Change visibility to the public"
How can I access private fields of inner private class to get and set data?
try this way its will work
public class firstClass{
private String name;
private String id;
Department dept;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
}
class Department{
private int departId;
private String deptName;
Course course;
public int getDepartId() {
return departId;
}
public void setDepartId(int departId) {
this.departId = departId;
}
public String getDeptName() {
return deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Course getCourse() {
return course;
}
public void setCourse(Course course) {
this.course = course;
}
}
class Course{
private int courseId;
public int getCourseId() {
return courseId;
}
public void setCourseId(int courseId) {
this.courseId = courseId;
}
}
You can't access private fields. Why don't you create a getter and setter for the inner class private fields?
And, maybe you should consider using gson library.
You at least have to make say nested public interfaces, say Dept and Course, with your private (static) nested private classes DeptImpl and SourceImpl.
public class X {
public interface Dept { ... }
private static class DeptImpl extends Dept { ... }
public Dept getDept() { ... }
public Dept createDept(...) {
DeptImpl dept = new DeptImpl(...); ...
return dept;
}
Maybe you need to provide a factory method createDept.
In some cases the implementing class can be anonymous new Dept() { ... }.
You can use Builder Design pattern with immutable Objects:
public class Class {
private final String name;
private final int id;
private final Department dept;
private Class(ClassBuilder classBuilder){
this.name = classBuilder.getName();
this.id = classBuilder.getId();
this.dept = classBuilder.getDept();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public Department getDept() {
return dept;
}
private static class Department{
private final int deptId;
private final String deptName;
private final Course course;
private Department(DepartmentBuilder departmentBuilder){
this.deptId = departmentBuilder.getDeptId();
this.deptName = departmentBuilder.getDeptName();
this.course = departmentBuilder.getCourse();
}
public int getDeptId() {
return deptId;
}
public String getDeptName() {
return deptName;
}
public Course getCourse() {
return course;
}
private static class Course{
private final int courseId;
private Course(CourseBuilder courseBuilder){
this.courseId = courseBuilder.getCourseId();
}
public int getCourseId() {
return courseId;
}
}
}
public static class ClassBuilder{
private final String name;
private final int id;
private final Department dept;
public ClassBuilder(String name, int id, Department dept){
this.name = name;
this.id = id;
this.dept = dept;
}
public Department getDept() {
return dept;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public Class build(){
return new Class(this);
}
}
public static class DepartmentBuilder {
private final int deptId;
private final String deptName;
private final Department.Course course;
public DepartmentBuilder(int deptId, String deptName, Department.Course course ){
this.deptId = deptId;
this.deptName = deptName;
this.course = course;
}
public int getDeptId() {
return deptId;
}
public String getDeptName() {
return deptName;
}
public Department.Course getCourse() {
return course;
}
public Department build(){
return new Department(this);
}
}
public static class CourseBuilder{
private final int courseId ;
public CourseBuilder(int courseId){
this.courseId = courseId;
}
public int getCourseId() {
return courseId;
}
public Department.Course build(){
return new Department.Course(this);
}
}
}
public class Sample {
public static void main(String ... strings){
Class clazz = new Class.ClassBuilder("ClassName", 1, new Class.DepartmentBuilder(1, "departmentName", new Class.CourseBuilder(2).build()).build()).build();
System.out.println(clazz.getDept());
}
}
I am just creating a handler in java which accepts a POJO called as ProductsModel.
public ProductsResponseObject handleRequest(ProductsRequestObject productsRequestObject, Context arg1) {
ProductsResponseObject respObj = null;
ProductsService productsService = new ProductsService();
arg1.getLogger().log("inside ProductsHandler.handleRequest with reqtype " + productsRequestObject.getReqType());
switch (productsRequestObject.getReqType()) {
case 0:
respObj = productsService.addProduct(productsRequestObject);
break;
case 1:
respObj = productsService.updateProduct(productsRequestObject);
break;
default:
break;
}
return respObj;
}
But here inside the handler method, the attributes of request, reqType and productModel are null. Not sure y?
Request POJO:
public class ProductsRequestObject {
private int reqType;
private ProductsModel productsModel;
public int getReqType() {
return reqType;
}
public void setReqType(int reqType) {
this.reqType = reqType;
}
public ProductsModel getProductsModel() {
return productsModel;
}
public void setProductsModel(ProductsModel productsModel) {
this.productsModel = productsModel;
}
}
Model POJO:
public class ProductsModel {
private String id;
private String dealerMobNumber;
private String name;
private String description;
private String price;
#DynamoDBHashKey(attributeName = "Id")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDealerMobNumber() {
return dealerMobNumber;
}
public void setDealerMobNumber(String dealerMobNumber) {
this.dealerMobNumber = dealerMobNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public class Media implements java.io.Serializable {
private int id;
private MediaKind mediaKind;
private String name;
private byte[] cover;
private Date releaseDate;
private Integer contentRating;
private String summary;
private Set mediaCrews = new HashSet(0);
private Set mediaInstances = new HashSet(0);
private Set ratings = new HashSet(0);
private Set genres = new HashSet(0);
static SessionFactory mediaFactory=Main.config.buildSessionFactory();
public Media() {
}
public Media(int id, MediaKind mediaKind, String name) {
this.id = id;
this.mediaKind = mediaKind;
this.name = name;
Session mediaSession = mediaFactory.getCurrentSession();
}
public Media(int id, MediaKind mediaKind, String name, byte[] cover,
Date releaseDate, Integer contentRating, String summary,
Set mediaCrews, Set mediaInstances, Set ratings, Set genres) {
this.id = id;
this.mediaKind = mediaKind;
this.name = name;
this.cover = cover;
this.releaseDate = releaseDate;
this.contentRating = contentRating;
this.summary = summary;
this.mediaCrews = mediaCrews;
this.mediaInstances = mediaInstances;
this.ratings = ratings;
this.genres = genres;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public MediaKind getMediaKind() {
return this.mediaKind;
}
public void setMediaKind(MediaKind mediaKind) {
this.mediaKind = mediaKind;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public byte[] getCover() {
return this.cover;
}
public void setCover(byte[] cover) {
this.cover = cover;
}
public Date getReleaseDate() {
return this.releaseDate;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
public Integer getContentRating() {
return this.contentRating;
}
public void setContentRating(Integer contentRating) {
this.contentRating = contentRating;
}
public String getSummary() {
return this.summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public Set getMediaCrews() {
return this.mediaCrews;
}
public void setMediaCrews(Set mediaCrews) {
this.mediaCrews = mediaCrews;
}
public Set getMediaInstances() {
return this.mediaInstances;
}
public void setMediaInstances(Set mediaInstances) {
this.mediaInstances = mediaInstances;
}
public Set getRatings() {
return this.ratings;
}
public void setRatings(Set ratings) {
this.ratings = ratings;
}
public Set getGenres() {
return this.genres;
}
public void setGenres(Set genres) {
this.genres = genres;
}
public static java.util.List<Media> search(String name){
java.util.List list;
Session sess=mediaFactory.getCurrentSession();
sess.beginTransaction();
Criteria criteria=sess.createCriteria(Media.class);
criteria.add(Restrictions.like("name", "%"+name+"%"));
list= criteria.list();
Hibernate.initialize(list);
sess.getTransaction().commit();
//connection=sess.close();
return list;
}
public ArrayList<MediaInstance> availableInstances(){
//sess.beginTransaction();
Session sess=mediaFactory.openSession();
sess.beginTransaction();
Criteria criteria=sess.createCriteria(MediaInstance.class);
criteria.add(Restrictions.like("media", name));
sess.getTransaction().commit();
return (ArrayList<MediaInstance>)criteria.list();
/*MediaInstance[] instances=(MediaInstance[]) mediaInstances.toArray();
ArrayList<MediaInstance> mediaInstanceList=new ArrayList<MediaInstance>(Arrays.asList(instances));
for(int i=0;i<mediaInstanceList.size();i++){
MediaInstance instance=mediaInstanceList.get(i);
if(!instance.isAvailable()|!instance.isSellable()){
mediaInstanceList.remove(instance);
}
}
//sess.getTransaction().commit();
//sess.close();
return mediaInstanceList;*/
}
}
here is my second class mediaInstance:
public class MediaInstance implements java.io.Serializable {
private int id;
private MediaType mediaType;
private Media media;
private String price;
private boolean available;
private boolean sellable;
private Set rents = new HashSet(0);
private Set purchases = new HashSet(0);
public MediaInstance() {
}
public MediaInstance(int id, MediaType mediaType, Media media,
String price, boolean available, boolean sellable) {
this.id = id;
this.mediaType = mediaType;
this.media = media;
this.price = price;
this.available = available;
this.sellable = sellable;
}
public MediaInstance(int id, MediaType mediaType, Media media,
String price, boolean available, boolean sellable, Set rents,
Set purchases) {
this.id = id;
this.mediaType = mediaType;
this.media = media;
this.price = price;
this.available = available;
this.sellable = sellable;
this.rents = rents;
this.purchases = purchases;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public MediaType getMediaType() {
return this.mediaType;
}
public void setMediaType(MediaType mediaType) {
this.mediaType = mediaType;
}
public Media getMedia() {
return this.media;
}
public void setMedia(Media media) {
this.media = media;
}
public String getPrice() {
return this.price;
}
public void setPrice(String price) {
this.price = price;
}
public boolean isAvailable() {
return this.available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public boolean isSellable() {
return this.sellable;
}
public void setSellable(boolean sellable) {
this.sellable = sellable;
}
public Set getRents() {
return this.rents;
}
public void setRents(Set rents) {
this.rents = rents;
}
public Set getPurchases() {
return this.purchases;
}
public void setPurchases(Set purchases) {
this.purchases = purchases;
}
}
When I try to call criteria.list() in method availableInstances() I get this exception.
May 27, 2014 1:22:56 PM org.hibernate.property.BasicPropertyAccessor$BasicGetter get
ERROR: HHH000122: IllegalArgumentException in class: Media, getter method of property: id
Exception in thread "main" org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of Media.id
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:192)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:346)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4746)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4465)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:243)
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:293)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
at org.hibernate.loader.Loader.bindPositionalParameters(Loader.java:1994)
at org.hibernate.loader.Loader.bindParameterValues(Loader.java:1965)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1682)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at MediaInstance.availableInstances(MediaInstance.java:125)
at Main.main(Main.java:24)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:169)
... 23 more
I used JBoss tools to generate the classes and mapping files from my database.
so I don't think that the problem is in mapping files.
Your criteria query doesn't seem right. You are trying to filter by an instance of media entity but passing the name as parameter.
Try something like this:
criteria.add(Restrictions.eq("media", this));
The second argument passed to the static "like" method (or "eq" method, and so on) of the Restrictions static class must be of the same type of the field identified by the first string (first argument).
In your example:
criteria.add(Restrictions.like("media", name));
"name" is a String while "media" field of the MediaInstance class is a instance of Media. You should substitute "name" with a media instance, even the Media instance itself executing the "availableInstances" method, so:
criteria.add(Restrictions.like("media", this));
I have a json string something similar
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","geo_position":{"latitude":52.39886,"longitude":13.06566}},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","geo_position":{"latitude":44.66978,"longitude":-74.98131}}]}
I am trying to convert to
{"results":
[{"_type":"Position","_id":377078,"name":"Potsdam, Germany","type":"location","latitude":52.39886,"longitude":13.06566},
{"_type":"Position","_id":410978,"name":"Potsdam, USA","type":"location","latitude":44.66978,"longitude":-74.98131}]}
I am converting to java and again converting back using But I am gettin null in data
SourceJSON data=new Gson().fromJson(jsonArray, SourceJSON.class);
DestinationJSON destdata = new DestinationJSON();
destdata.setLatitide(data.getGeoLocation().getLatitide());
destdata.setLongitude(data.getGeoLocation().getLongitude());
destdata.setId(data.getId());
destdata.setType(data.getType());
destdata.setName(data.getName());
destdata.set_type(data.get_type());
Gson gson = new Gson();
String json = gson.toJson(destdata);
below are my beans
public class SourceJSON implements Serializable {
private List<GEOLocation> geoLocations;
private String _type;
private String id;
private String name;
private String type;
public String get_type() {
return _type;
}
public List<GEOLocation> getGeoLocations() {
return geoLocations;
}
public void setGeoLocations(List<GEOLocation> geoLocations) {
this.geoLocations = geoLocations;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
and
public class GEOLocation implements Serializable{
private String latitide;
private String longitude;
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
and destination java
public class DestinationJSON implements Serializable {
private String _type;
private String id;
private String name;
private String type;
private String latitide;
private String longitude;
public String get_type() {
return _type;
}
public void set_type(String _type) {
this._type = _type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getLatitide() {
return latitide;
}
public void setLatitide(String latitide) {
this.latitide = latitide;
}
public String getLongitude() {
return longitude;
}
public void setLongitude(String longitude) {
this.longitude = longitude;
}
}
All you need is this. You can try this class in your IDE with a simple copy&paste.
package stackoverflow.questions;
import java.util.*;
import com.google.gson.Gson;
public class Q20433539{
public static void main(String[] args){
String json = "{\"results\":"+
"[{\"_type\":\"Position\",\"_id\":377078,\"name\":\"Potsdam, Germany\",\"type\":\"location\",\"geo_position\":{\"latitude\":52.39886,\"longitude\":13.06566}},"+
"{\"_type\":\"Position\",\"_id\":410978,\"name\":\"Potsdam, USA\",\"type\":\"location\",\"geo_position\":{\"latitude\":44.66978,\"longitude\":-74.98131}}]}";
Gson gson = new Gson();
Map m = gson.fromJson(json, Map.class);
List<Map> innerList = (List<Map>) m.get("results");
for(Map result: innerList){
Map<String, Double> geo_position = (Map<String, Double>) result.get("geo_position");
result.put("latitude", geo_position.get("latitude"));
result.put("longitude", geo_position.get("longitude"));
result.remove("geo_position");
}
System.out.println(gson.toJson(m));
}
}
Of course, it works under the assumption that you always want to flat geo information.
Explanation: It's convenient to use POJO when working with Gson, but it's not the only way. Gson can also deseralize to Arrays/Maps if you do not specify the expected result. So I did, and then I manipulated the structure to unfold your data. After that, Gson can serialize Arrays/Maps structure again to your desidered JSON.
I'm using XmlAdapter for immutable objects as proposed in this blog post: http://blog.bdoughan.com/2010/12/jaxb-and-immutable-objects.html. This works fine, but not with references to other immutable objects in my adapters. Is there any way to handle this with JAXB?
Below there is an example which does not work if the person's xml tag comes after the company's xml tag which references the person.
Immutable objects:
#XmlJavaTypeAdapter(PersonAdapter.class)
public class Person {
private final String id;
private final String name;
public Person(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
}
#XmlJavaTypeAdapter(CompanyAdapter.class)
public class Company {
private final String name;
private final Person principal;
public Company(String name, Person principal) {
this.name = name;
this.principal = principal;
}
public String getName() {
return name;
}
public Person getPrincipal() {
return principal;
}
}
PersonAdapter:
public class PersonAdapter extends XmlAdapter<AdaptedPerson, Person> {
public static class AdaptedPerson {
#XmlID
#XmlAttribute
String id;
#XmlAttribute
String name;
}
#Override
public AdaptedPerson marshal(Person v) throws Exception {
AdaptedPerson a = new AdaptedPerson();
a.id = v.getId();
a.name = v.getName();
return a;
}
#Override
public Person unmarshal(AdaptedPerson v) throws Exception {
return new Person(v.id, v.name);
}
}
CompanyAdapter:
public class CompanyAdapter extends XmlAdapter<AdaptedCompany, Company> {
public static class AdaptedCompany {
#XmlAttribute
String name;
#XmlIDREF
#XmlAttribute
Person principal;
}
#Override
public AdaptedCompany marshal(Company v) throws Exception {
AdaptedCompany a = new AdaptedCompany();
a.name = v.getName();
a.principal = v.getPrincipal();
return a;
}
#Override
public Company unmarshal(AdaptedCompany v) throws Exception {
return new Company(v.name, v.principal);
}
}