Using MapConverter in XStream

橙三吉。 提交于 2020-01-05 12:36:56

问题


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>

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"));

And I'm getting an exception:

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());

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.

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!


回答1:


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.

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.



来源:https://stackoverflow.com/questions/25096667/using-mapconverter-in-xstream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!