我怎样才能获得像这样的简单JSON结构
{
"id": 9901,
"name": "Reader",
"value": true
}
使用JAXB注释和那段代码? (UserInfo应包含相同层次结构级别的枚举字段)
@XmlRootElement
public class UserInfo
{
private UserLevel level;
@XmlElement ( name = "value" )
private boolean allowed;
}
public enum UserLevel
{
READER ( "Reader", 9901 ),
TESTER ( "Tester", 9903 );
private final String name;
private final int id;
private UserLevel( String name, int id )
{
this.name = name;
this.id = id;
}
get...()
}
答案 0 :(得分:0)
一个解决方案是让另一个JAXB类与你想要的JSON结构相匹配,就像这样(缺少构造函数):
@XmlRootElement
public class UserInfoFlattened
{
@XmlElement
private int id;
@XmlElement
private String name;
@XmlElement ( name = "value" )
private boolean allowed;
}
然后你应该在课程@XmlJavaTypeAdapter
上使用UserInfo
,它看起来像这样:
public class UserInfoAdapter extends XmlAdapter<UserInfoFlattened, UserInfo>
{
@Override
public UserInfoFlattened marshal( UserInfo userInfo )
{
return new UserInfoFlattened( userInfo.getValue(), userInfo.getUserLevel().getId(), userInfo.getUserLevel().getName() );
}
// unmarshal analogous
}