Question

I need to write some information into the JSON file.

I have written the following function:

public String toJSON() {
    StringBuffer sb = new StringBuffer();

    sb.append("\"" + MyConstants.VEHICLE_LABEL + "\":");
    sb.append("{");
    sb.append("\"" + MyConstants.CAPACITY1_LABEL + "\": " + String.valueOf(this.getCapacity(0)) +  ",");
    sb.append("\"" + MyConstants.CAPACITY2_LABEL + "\": " + String.valueOf(this.getCapacity(1)) +  ",");
    sb.append("\"" + MyConstants.CAPACITY3_LABEL + "\": " + String.valueOf(this.getCapacity(2)));   
    sb.append("}");

    return sb.toString();
}

However, I want to make this function more flexible. In particular, how should I change this code if the number of capacity units is not fixed (1, 2 or 3)?

I think that there should be a FOOR loop, however I am not sure how to implement it correctly.

Était-ce utile?

La solution

Well you could do the append only if this.getCapacity(i) is not empty.

You could do something like this with a for loop

for(int i=0; i < max; i++) {
    if(!StringUtils.isEmpty(String.valueOf(this.getCapacity(i)))){
        sb.append("\"" + String.format(MyConstants.CAPACITY_LABEL, i) + "\": " + String.valueOf(this.getCapacity(i)) +  ",");
    }
}

where MyConstants.CAPACITY_LABEL is something like "capacity%d_label"

But, as azurefrog said, I would use a json parser to do this.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top