我需要将一些信息写入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解析器来执行此操作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句