1 回答

TA貢獻1808條經(jīng)驗 獲得超4個贊
正如評論中提到的@fabian - 您應該首先解析文件內容,修改并覆蓋文件。這是一個示例代碼如何實現(xiàn)這一點:
首先,我不知道您使用的是什么 json 庫,但我強烈建議使用以下內容:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
它通常會簡化您使用 json 的工作。如果您不想使用庫,您仍然可以按照說明進行操作,但可以根據(jù)您的需要進行調整。整個實現(xiàn)是這樣的:
public class JSONWriteExample {
private static final String FILE_NAME = "jsonArray.json";
private static final Path FILE_PATH = Paths.get(FILE_NAME);
private final String type;
private final int quantity;
public JSONWriteExample(String type, int quantity) {
this.type = type;
this.quantity = quantity;
}
public void jsonParse() throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
if (Files.notExists(FILE_PATH)) {
Files.createFile(FILE_PATH);
objectMapper.writeValue(FILE_PATH.toFile(), createItems(new ArrayList<>()));
}
Items items = objectMapper.readValue(FILE_PATH.toFile(), Items.class);
final List<Item> itemsList = items.getItems();
objectMapper.writeValue(FILE_PATH.toFile(), createItems(itemsList));
}
private Items createItems(List<Item> itemsList) {
final Item item = new Item();
item.setType(type);
item.setQuantity(quantity);
itemsList.add(item);
final Items items = new Items();
items.setItems(itemsList);
return items;
}
public static class Items {
private List<Item> items;
// Setters, Getters
}
public static class Item {
private String type;
private int quantity;
// Setters, Getters
}
}
好的,這段代碼發(fā)生了什么?
首先,請注意 Java 7 NIO 的用法——推薦的在 java 中處理文件的方法。
在
jsonParse
方法中,我們首先檢查文件是否存在。如果是 - 然后我們將其讀取到
Items
描述我們模型的數(shù)據(jù)類 ( ) 中。閱讀部分是在這個庫的底層完成的,只是你的 json 文件的文件應該與數(shù)據(jù)類的字段同名(或用JsonAlias
annotation.xml 指定)。如果沒有 - 那么我們首先創(chuàng)建它并填充初始值。
ObjectMapper
是庫中的類,用于讀取\寫入 json 文件。
現(xiàn)在,如果我們運行這段代碼,例如
public static void main(String[] args) throws IOException {
JSONWriteExample example = new JSONWriteExample("TV", 3);
example.jsonParse();
JSONWriteExample example2 = new JSONWriteExample("phone", 3);
example2.jsonParse();
}
json 文件將如下所示:
{
"items": [
{
"type": "TV",
"quantity": 3
},
{
"type": "TV",
"quantity": 3
},
{
"type": "phone",
"quantity": 3
}
]
}
添加回答
舉報