如何在运行时从 Java 接口向 json 数组添加元素

我想在运行时将元素从 Java GUI 添加到 JSON 数组


但每次在 JSON 文件中创建新数组时


Java GUI 输入数据:


String _itemType = txtItemType.getText();

int _itemQuantity = Integer.parseInt(txtItemQuantity.getText());

JSONWriteExample obj = new JSONWriteExample(_itemType, _itemQuantity);

obj.jsonParse();

JSON:


public JSONWriteExample(String type, int number) {

    this.type = type;

    this.quantity = number;  

}


public void jsonParse() throws IOException {

    JSONObject jo = new JSONObject(); 

    Map m = new LinkedHashMap(4); 

    JSONArray ja = new JSONArray(); 


    m = new LinkedHashMap(2); 

    m.put("Item Type", type); 

    m.put("Quantity", quantity);       

    ja.add(m); 

    jo.put("Items", ja); 

    FileWriter file=new FileWriter("jsonArray.json",true);

    file.append(jo.toString());

    file.flush(); 

    file.close(); 

}

我希望输出如下:


{  

   "Items":[  

      {  

         "Item Type":"TV",

         "Quantity":3

      },

      {  

         "Item Type":"phone",

         "Quantity":3

      }

   ]

}

但是每次都会创建新数组,例如:


{  

   "Items":[  

      {  

         "Item Type":"TV",

         "Quantity":3

      }

   ]

}{  

   "Items":[  

      {  

         "Item Type":"phone",

         "Quantity":3

      }

   ]

}


回首忆惘然
浏览 292回答 1
1回答

炎炎设计

正如评论中提到的@fabian - 您应该首先解析文件内容,修改并覆盖文件。这是一个示例代码如何实现这一点:首先,我不知道您使用的是什么 json 库,但我强烈建议使用以下内容:<dependency>&nbsp; &nbsp; <groupId>com.fasterxml.jackson.core</groupId>&nbsp; &nbsp; <artifactId>jackson-databind</artifactId>&nbsp; &nbsp; <version>2.9.8</version></dependency>它通常会简化您使用 json 的工作。如果您不想使用库,您仍然可以按照说明进行操作,但可以根据您的需要进行调整。整个实现是这样的:public class JSONWriteExample {&nbsp; &nbsp; private static final String FILE_NAME = "jsonArray.json";&nbsp; &nbsp; private static final Path FILE_PATH = Paths.get(FILE_NAME);&nbsp; &nbsp; private final String type;&nbsp; &nbsp; private final int quantity;&nbsp; &nbsp; public JSONWriteExample(String type, int quantity) {&nbsp; &nbsp; &nbsp; &nbsp; this.type = type;&nbsp; &nbsp; &nbsp; &nbsp; this.quantity = quantity;&nbsp; &nbsp; }&nbsp; &nbsp; public void jsonParse() throws IOException {&nbsp; &nbsp; &nbsp; &nbsp; ObjectMapper objectMapper = new ObjectMapper();&nbsp; &nbsp; &nbsp; &nbsp; if (Files.notExists(FILE_PATH)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Files.createFile(FILE_PATH);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; objectMapper.writeValue(FILE_PATH.toFile(), createItems(new ArrayList<>()));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; Items items = objectMapper.readValue(FILE_PATH.toFile(), Items.class);&nbsp; &nbsp; &nbsp; &nbsp; final List<Item> itemsList = items.getItems();&nbsp; &nbsp; &nbsp; &nbsp; objectMapper.writeValue(FILE_PATH.toFile(), createItems(itemsList));&nbsp; &nbsp; }&nbsp; &nbsp; private Items createItems(List<Item> itemsList) {&nbsp; &nbsp; &nbsp; &nbsp; final Item item = new Item();&nbsp; &nbsp; &nbsp; &nbsp; item.setType(type);&nbsp; &nbsp; &nbsp; &nbsp; item.setQuantity(quantity);&nbsp; &nbsp; &nbsp; &nbsp; itemsList.add(item);&nbsp; &nbsp; &nbsp; &nbsp; final Items items = new Items();&nbsp; &nbsp; &nbsp; &nbsp; items.setItems(itemsList);&nbsp; &nbsp; &nbsp; &nbsp; return items;&nbsp; &nbsp; }&nbsp; &nbsp; public static class Items {&nbsp; &nbsp; &nbsp; &nbsp; private List<Item> items;&nbsp; &nbsp; &nbsp; &nbsp; // Setters, Getters&nbsp; &nbsp; }&nbsp; &nbsp; public static class Item {&nbsp; &nbsp; &nbsp; &nbsp; private String type;&nbsp; &nbsp; &nbsp; &nbsp; private int quantity;&nbsp; &nbsp; &nbsp; &nbsp; // Setters, Getters&nbsp; &nbsp; }&nbsp;}好的,这段代码发生了什么?首先,请注意 Java 7 NIO 的用法——推荐的在 java 中处理文件的方法。在jsonParse方法中,我们首先检查文件是否存在。如果是 - 然后我们将其读取到Items描述我们模型的数据类 ( ) 中。阅读部分是在这个库的底层完成的,只是你的 json 文件的文件应该与数据类的字段同名(或用JsonAliasannotation.xml 指定)。如果没有 - 那么我们首先创建它并填充初始值。ObjectMapper是库中的类,用于读取\写入 json 文件。现在,如果我们运行这段代码,例如public static void main(String[] args) throws IOException {&nbsp; &nbsp; JSONWriteExample example = new JSONWriteExample("TV", 3);&nbsp; &nbsp; example.jsonParse();&nbsp; &nbsp; JSONWriteExample example2 = new JSONWriteExample("phone", 3);&nbsp; &nbsp; example2.jsonParse();}json 文件将如下所示:{&nbsp; "items": [&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "type": "TV",&nbsp; &nbsp; &nbsp; "quantity": 3&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "type": "TV",&nbsp; &nbsp; &nbsp; "quantity": 3&nbsp; &nbsp; },&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; "type": "phone",&nbsp; &nbsp; &nbsp; "quantity": 3&nbsp; &nbsp; }&nbsp; ]}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java