peter-varga-sp
12/19/2016 - 1:53 PM

Builder class that can be used by Eclipse IDE to generate a JSON style toString() method

Builder class that can be used by Eclipse IDE to generate a JSON style toString() method

package com.mydevnotes.eclipse.tostringbuilder;

import org.apache.commons.lang3.builder.Builder;

/**
 * Builds a toString() method for Eclipse IDE, that generates the toString result in JSON format.</br>
 * Implements the {@link Builder} interface, in order to make Eclipse possible to use the fluent API (chaining) for generating the toString() method.
 * 
 * @author Peter Varga
 *
 */
public class JsonToStringBuilder implements Builder<String> {

    private StringBuilder sb = new StringBuilder();

    /**
     * Constructor with Object parameter. Required by the Eclipse ToString() builder.
     * 
     * @param o
     */
    public JsonToStringBuilder(Object o) {
	super();
    }

    /**
     * Appends a field - value pair to the generated toString() method.
     * 
     * @param fieldName
     * @param fieldValue
     * @return
     */
    public JsonToStringBuilder append(final String fieldName, final Object fieldValue) {
	sb.append(sb.length() == 0 ? "" : ",").append("\"").append(fieldName).append("\" : \"").append(fieldValue == null ? "null" : fieldValue)
		.append("\"");
	return this;
    }

    /**
     * Builds the String representation of the object
     */
    public String build() {
	return "{" + sb.toString() + "}";
    }

}