我需要将一些信息写入 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 解析器来执行此操作。
关于java - 将数据写入json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23684134/