Today, when I was creating a RESTful service in JavaEE for a dynamic web application to run in IBM® WebSphere Application Server (WAS) an error like this was appearing:
Class has two properties of the same name "userId" this problem is related to the following location: at public java.lang.String com.rest.model.UserProfile.getUserId() at com.rest.model.UserProfile this problem is related to the following location: at private java.lang.String com.rest.model.UserProfile.userId at com.rest.model.UserProfile
After looking for documentation and all related issues, I found a solution that I would like to share with you:
1) My class looked like this:
package com.rest.model; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlType; /** * @author Alex Arriaga */ @XmlRootElement(name = "profile") public class UserProfile{ @XmlElement(name="user_id") private String userId; // More code here... public UserProfile(){ } public UserProfile(String s){ this.test = s; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } // More code here... }
2) How to fix it
It was really easy after spending time to search this issue. My JAXB was looking at both the getUserId() method and the member userId. I didn’t say which JAXB implementation I was using, the exception was fairly clear but that was the first time that I was working with JABX, at the beginning it is a little complicated to understand that message.
To solve this issue just was necessary to specify to JAXB which implementation I wanted to use using @XmlAccessorType(XmlAccessType.FIELD) annotation after @XmlRootElement(name = “profile”) please, see next code to have a clearer idea.
package com.rest.model; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlType; /** * @author Alex Arriaga * */ @XmlRootElement(name = "profile") @XmlAccessorType(XmlAccessType.FIELD) // This line was added public class UserProfile{ @XmlElement(name="user_id") private String userId; // More code here... public UserProfile(){ } public UserProfile(String s){ this.test = s; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } // More code here... }
That’s it!
Be happy with your code.