Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java XStream with HashMap

Tags:

java

json

xstream

I want to use XStream to convert a java hash to a json hash. I feel like this should be easier than it seems. What I'm looking for is a way to make:

Map<String, String> map = new HashMap<String, String>();
map.put("first", "value1");
map.put("second", "value2");

become

{'first' : 'value1', 'second' : 'value2' }

The closes I have converts it into a series of arrays.

XStream xstream = new XStream(new JettisonMappedXmlDriver() {
    public HierarchicalStreamWriter createWriter(Writer writer) {
        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
    }
});

xstream.toXML(map);

which becomes

[["first", "value1"], ["second", "value2"]]

I feel like converting a java hash to json hash should be straight forward. Am I missing something?

like image 722
Ken Mazaika Avatar asked Nov 15 '11 18:11

Ken Mazaika


1 Answers

The thing is that XStream is first and foremost designed to marshal and unmarshal Java objects to XML, JSON being just an afterthought, it most certainly has the least elegant support.

The technical problem being that as XStream must support both - XML and JSON formats, JSON map representation suffers, as there is no native way to represent a map-like structures in XML.

like image 87
Roland Tepp Avatar answered Oct 27 '22 16:10

Roland Tepp