在 XStream 中使用 MapConverter [英] Using MapConverter in XStream

查看:48
本文介绍了在 XStream 中使用 MapConverter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 XML 代码转换为 Java Map.XML(int 一个不同的文件)看起来像这样,并用数字匹配单词(概率分布):

I'm trying to convert XML Code into a Java Map. The XML (int a different file) looks something like this, and matches words with numbers (a probability distribution):

<?xml version="1.0" encoding="UTF-8" ?>
<root>
   <Durapipe type="int">1</Durapipe>
   <EXPLAIN type="int">2</EXPLAIN>
   <woods type="int">2</woods>
   <hanging type="int">3</hanging>
   <hastily type="int">2</hastily>
   <localized type="int">1</localized>
   <Schuster type="int">5</Schuster>
   <regularize type="int">1</regularize>
   <LASR type="int">1</LASR>
   <LAST type="int">22</LAST>
   <Gelch type="int">2</Gelch>
   <Gelco type="int">26</Gelco>
   .......
</root>

我目前使用的 Java 代码如下所示:

The Java code that I'm using currently looks like this:

    XStream xstream = new XStream();        
    Map<String, Integer> englishCorpusProbDist; 
    englishCorpusProbDist = (Map<String, Integer>)xstream.fromXML(new File("locationonmycomputer/frequencies.xml"));

我遇到了一个例外:

Exception in thread "main" com.thoughtworks.xstream.mapper.CannotResolveClassException: root
at com.thoughtworks.xstream.mapper.DefaultMapper.realClass(DefaultMapper.java:79)

有人建议我使用以下方法注册我的转换器:

It was suggested that I register my Converter using the following:

xstream.registerConverter(new MapEntryConverter());

问题在于 MapEntryConverter 似乎不是 XStream 中的一个类,我对这个人的建议感到困惑.

The problem with that is that MapEntryConverter doesn't seem to be a class in XStream, and I'm confused with this person's suggestion.

这是我在此人的回答中提出的上一个问题:将 XML 转换为 Java Map

Here's the previous question I asked about this with the person's response: Converting XML into Java Map<String, Integer>

任何帮助将不胜感激.提前致谢!

Any help would be much appreciated. Thank you in advance!

推荐答案

你实际上需要实现你自己的*MapConverter,它扩展了Converter;没有名为 MapConverter 的实际类,这也是我有一段时间感到困惑的东西.

You actually need to implement your own *MapConverter which extends Converter; there is no actual class called MapConverter which is something I was confused with for a while as well.

看看我在 Github.我希望这会让事情更容易理解.您基本上必须告诉 XStream 在编组和解组与相应标签相关的数据时要做什么.

Have a look at one that I've implemented and have on Github. I hope this would make things more understandable. You basically have to tell XStream what to do when marshalling and unmarshalling the data related to the respective tag.

这篇关于在 XStream 中使用 MapConverter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆