簡體   English   中英

將數據寫入json文件

[英]Writing data into json file

我需要將一些信息寫入JSON文件。

我寫了以下函數:

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();
}

但是,我想使此功能更靈活。 特別是如果容量單位的數量不固定(1、2或3),我應該如何更改此代碼?

我認為應該有一個FOOR循環,但是我不確定如何正確實現它。

好吧,僅當this.getCapacity(i)不為空時,才可以執行追加操作。

您可以使用for循環執行類似的操作

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)) +  ",");
    }
}

MyConstants.CAPACITY_LABEL類似於“ capacity%d_label”

但是,正如azurefrog所說,我將使用json解析器來執行此操作。

您可以嘗試遵循流行的構建器模式的以下類:

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();
    }
}

然后在您的主要方法中調用:

   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();

然后,只要您願意,就可以保持鏈接的appendSimpleValue方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM