gpt4 book ai didi

java - 无法让简单的 XmlAdapter 工作

转载 作者:行者123 更新时间:2023-11-30 11:52:19 26 4
gpt4 key购买 nike

我正在尝试让 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 信息,值得一试。

最佳答案

我想出了解决问题的方法,即使我不明白发生了什么。

我在这个项目中使用了 Spring 框架,我的 XmlAdapter 类被标记为 @Component。删除该注释使代码完美运行。出于某种原因,让我的适配器由 Spring 管理会阻止我的 JAXB 提供程序使用该类来解码我的 XML。

关于java - 无法让简单的 XmlAdapter 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6906614/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com