我有以下内容Enum
:
public enum MyState {
Open("opened"),
Close("closed"),
Indeterminate("unknown");
private String desc;
private MyState(String desc) {
setDesc(desc);
}
public String getDesc() {
return this.desc;
}
private void setDesc(String desc) {
this.desc = desc;
}
}
我正在尝试编写一个 XStream Converter
,它知道将 JSON 元素“ mystate
”映射回一个MyState
实例。
"someJson": {
"object1": {
"mystate": closed
}
}
除了其他对象(someJson
和object1
)之外,这应该产生一个MyState.Close
实例。我已经开始了Converter
,但还没有走得很远:
public class MyStateEnumConverter implement Converter {
@Override
public boolean canConvert(Class clazz) {
return clazz.equals(MyState.class);
}
@Override
public void marshal(Object value, HierarchialStreamWriter writer, MarshallingContext context) {
??? - no clue here
}
@Override
public Object unmarshal(HierarchialStreamReader reader, UnmarshallingContext context) {
??? - no clue here
}
}
然后,创建映射器并使用它:
XStream mapper = new XStream(new JettisonMappedXmlDriver());
mapper.registerConverter(new MyStateEnumConverter);
SomeJson jsonObj = mapper.fromXML(jsonString);
// Should print "closed"
System.out.println(jsonObject.getObject1().getMyState().getDesc());
如何实现marshal
并unmarshal
获得所需的映射?提前致谢!