Search code examples
javajsonpropertiesxstream

xstream json: convert java.util.Properties to object literal


I am using xstream to de/serialize objects to json.

I want to serialize a java.util.Properties but I want it to be serialized in javascript as a object literal.

I.e. Properties p = new Properties(); p.setProperty("a", "b"); p.setProperty("x", "y");

should be converted to:

{a: 'b', x: 'y'}

Solution

  • It is not easy with XStream, because XStream first marshals the Properties object into intermediary XML before converting the XML to JSON and getting the XML just right is hard.

    It would be far easier to loop over the Properties and build the JSON string directly. For example, like this:

    StringBuilder builder = new StringBuilder() ;
    builder.append('{');
    Enumeration keys = props.keys();
    while (keys.hasMoreElements()) {
      String key = (String)keys.nextElement();
      String value = (String)props.get(key);
      builder.append('"').append(key).append('"');
      builder.append(':');
      builder.append('"').append(value).append('"').append(',');
    }
    builder.deleteCharAt(builder.length()-1);
    builder.append('}');
    String json = builder.toString();