我正在尝试让一个XmlAdapter到HashMap工作,我不断得到一个异常。我非常密切地关注this blog entry,而且我已多次查看我的代码,但我没有看到问题。
我使用最新版本的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
的位置。有时输入一个问题会让我得到答案但不是这次。
我确信这很简单 - 如果你看到我的错误,请指出来!
谢谢!
顺便说一下,Blaise Doughan's blog充满了很棒的JAXB和MOXy信息,值得一试。
答案 0 :(得分:1)
我想到了如何解决这个问题,即使我不明白发生了什么。
我在这个项目中使用Spring框架,我的XmlAdapter
类被标记为@Component
。删除该注释使代码完美运行。由于某种原因,由Spring管理的适配器阻止了我的JAXB提供程序使用该类来解组我的XML。
答案 1 :(得分:0)
您可以参考XmlAdapter的官方文档。他们给出了相同的例子。