Java XStream with HashMap

I want to use XStream to convert a java hash to a json hash. I feel it should be easier than it sounds. I am looking for a way:

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

to become

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

Closes, I convert it to 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"]] 

It seems to me that converting a java hash to a Json hash should be straightforward. Did I miss something?

+6
source share
3 answers

The fact is that XStream is primarily intended for marshalling and disassembling Java objects in XML, JSON is just an afterthought, it certainly has the least elegant support.

The technical problem is that since the XStream must support both XML and JSON formats, the representation of the JSON map suffers because there is no native way of representing structures like the map in XML.

+1
source

I had similar problems when converting to jSon. My solution to this problem was to have a string already formatted in JSon before dropping the file (in my case, the database). The most efficient process I came across was to create a toJson function inside my classes to work just like toString.

Example:

Converts an output string of object data to Json format

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

So, for you, implement a similar process while filling out your card.

0
source

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

Vocation:

 JSONObject jsobj = new JSONObject(map); String strJson = jsobj.toString(); 
0
source

Source: https://habr.com/ru/post/901542/


All Articles