You can try the following class that follows the popular builder pattern:
public class JsonVehicleBuilder {
private StringBuilder builder;
/**
* Starts off the builder with the main label
*/
public JsonVehicleBuilder(String mainLabel) {
builder = new StringBuilder();
builder.append("\"").append(mainLabel).append("\":");
builder.append("{");
}
public JsonVehicleBuilder appendSimpleValue(String label, String value) {
builder.append("\"").append(label).append("\":").append(value).append(",");
return this;
}
/**
* Appends the closing bracket and outputs the final JSON
*/
public String build() {
builder.deleteCharAt(builder.lastIndexOf(",")); //remove last comma
builder.append("}");
return builder.toString();
}
}
And then in your main method you would call:
JsonVehicleBuilder jsonVehicleBuilder = new JsonVehicleBuilder(MyConstants.VEHICLE_LABEL);
jsonVehicleBuilder.appendSimpleValue(MyConstants.CAPACITY1_LABEL,String.valueOf(this.getCapacity(0)))
.appendSimpleValue(MyConstants.CAPACITY2_LABEL,String.valueOf(this.getCapacity(1)))
.appendSimpleValue(MyConstants.CAPACITY3_LABEL,String.valueOf(this.getCapacity(2)));
String json = jsonVehicleBuilder.build();
You can then keep chaining the appendSimpleValue method as long as you like.