Search code examples
javajsontostring

Java: JSONObject.toString() - adding extra space after colon (":" -> ": ")


Been googling a while but haven't found anything useful since keywords are too common.

Currently in my Java code method toString() (called on some JSONObject object) produces output like this:

{"key_name":<numerical_value>}

while what I need (due to the fact that parser on the other side of the project is imperfect) is:

{"key_name": <numerical_value>}

The only difference is that extra space after colon. Is there any JSONObject builtin way to do it or do I need some handwritten simple string operation for it?


Solution

  • I can only imagine building a custom JSONStringer. In fact, it could be a JSONWriter built using a StringWriter. Then you override all the value methods to add a space before calling parent class method.

    class JSONSpaceStringer extends JSONWriter {
        private StringWriter sw;
    
        JSONSpaceStringer(StringWriter sw) {
            parent(sw); // initialize parent
            this.sw = sw;
        }
    
        @Override
        public JSONWriter value(long l) throws JSONException {
            sw.write(" "); // add an initial space
            parent.value(l); // and let parent class do the job...
        }
    
    // same for all other value methods
    //...
    }