我试图让一个XmlAdapter到一个HashMap来工作,而且我一直得到一个异常。我非常密切地跟踪这个博客条目,并且我已经多次检查我的代码,但是我没有看到这个问题。
我正在使用最新版本的org.eclipse.persistence.jaxb.JAXBContextFactory作为我的JAXB提供者。
下面是我的XML示例:
<test>
<myName>Paul</myName>
<mappings>
<entry key="man">manufacturer</entry>
<entry key="prod">product</entry>
</mappings>
<test>按照上面提到的博客文章中的步骤:
1.标识不可映射的类
我正在绘制java.util.HashMap地图。
2.创建一个可映射的等效类
public class MappingType
{
public List<MappingEntryType> entry = new ArrayList<MappingEntryType>();
}
public class MappingEntryType
{
@XmlAttribute
public String key;
@XmlValue
public String value;
}3.创建一个XmlAdapter以在不可映射对象和可映射对象之间进行转换()
public class MappingAdapter extends XmlAdapter<MappingType,
HashMap<String, String>>
{
@Override
public HashMap<String, String> unmarshal(MappingType v> throws Exception
{
HashMap<String, String> hashMap = new HashMap<String, String>();
for (MappingTypeEntry mappingEntry : v.entry)
{
hashMap.put(mappingEntry.key, mappingEntry.value);
}
return hashMap;
}
// marshal is here but I'm just working on unmarshalling now
}4.指定XmlAdapter
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "test")
public class TestEntity
{
@XmlElement
private String myName;
@XmlJavaTypeAdapter(MappingAdapter.class)
HashMap<String, String> mappings;
// getters & setters omitted in a feeble attempt at brevity
}我已经添加了下一步,我称之为5.堆栈跟踪
Exception [EclipseLink-3001](Eclipse Persistence Services-2.3.0.v20110604-r9504):
org.eclipse.persistence.exceptions.ConversionException
ExceptionDescription: The object [mypackage.MappingType@145d424], of class
[class mypackage.MappingType],could not be converted to [class java.util.HashMap]
at etc etc异常描述非常清楚,但我看不到我试图将MappingType转换为HashMap的位置。有时候,输入一个问题会让我找到答案,但这次不会。
我相信这很简单--如果你看到我的错误,请指出!
谢谢!
顺便说一句,布莱斯·道根的博客充满了出色的JAXB和MOXy信息,值得一看。
发布于 2011-08-02 03:09:07
我想好了如何解决这个问题,即使我不明白发生了什么。
我在这个项目中使用了Spring框架,我的XmlAdapter类被标记为@Component。删除该注释使代码完美地工作。出于某种原因,让Spring管理我的适配器,阻止了JAXB提供程序使用该类来解除XML的封送。
发布于 2012-06-06 05:51:55
您可以参考XmlAdapter的办公室文档。他们也举了同样的例子。
https://stackoverflow.com/questions/6906614
复制相似问题