gpt4 book ai didi

java - 将数据写入json文件

转载 作者:行者123 更新时间:2023-11-30 03:54:09 32 4
gpt4 key购买 nike

我需要将一些信息写入 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/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com