I have a class TestCase. Inside of this I have the inner class Test. Inside the class enum OwnerType with setters and getters of the enum.
public static final class Test {
public enum OwnerType {
User("User"), Role("Role");
private final String value;
private OwnerType(String value) {
this.value = value;
}
public String toValue() {
return value;
}
}
private OwnerType m_ownerType;
public OwnerType getOwnerType() {
return m_ownerType;
}
public void setOwnerType(OwnerType m_ownerType) {
this.m_ownerType = m_ownerType;
}
private JSONObject getJSONObject() {
JSONObject obj = new JSONObject();
obj.put(KEY, new JSONString(m_ownerType.toString())); // Showing Error Enum to String Conversion
return obj;
}
}
m_ownerType
is OwnerType Enum
so in obj.put()
I am doing wrong related with some conversion from enum to string.
Thanks.
Java枚举带有内置函数name()
,这是将它们序列化为字符串的首选方法。
Take a look at Three ways to Serialize Java Enums . It depends on your use case but using the name()
method looks fine in most use cases.
All you really need in an enum
is this:
public enum OwnerType {
User,
Role
}
And to get its value as String you can call .name()
or .toString()
:
OwnerType ot = OwnerType.User;
System.out.println("Owner is of type: " + ot.name());
That will print out "Owner is of type: User" . The next two will produce the same result:
System.out.println("Owner is of type: " + ot.toString());
System.out.println("Owner is of type: " + ot); // Implicit call to toString()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.