6

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?

Ken Mazaika
  • 1,142
  • 10
  • 12

3 Answers3

2

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.

Roland Tepp
  • 8,301
  • 11
  • 55
  • 73
0

I had similar issues when converting to jSon. My solution to this problem was to have the string already formatted to JSon before dropping into the file (in my case a database). The most efficient process I have come up with so far was to create a toJson function inside my classes to work just like toString.

Example:

Converts the objects data output string into Json format

public JsonObject toJson()
   {

       JsonObject temp = new JsonObject();
       temp.addProperty(tagName,floatData);
       return temp;
    }

So for you, implement a similar process while populating your map.

hd1
  • 33,938
  • 5
  • 80
  • 91
Daniel Haro
  • 341
  • 1
  • 2
  • 11
0

You can try to use the "official" json lib for java from json.org.

Calling:

JSONObject jsobj = new JSONObject(map);
String strJson = jsobj.toString();
DNax
  • 1,413
  • 1
  • 19
  • 29