第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在運行時從 Java 接口向 json 數(shù)組添加元素

如何在運行時從 Java 接口向 json 數(shù)組添加元素

回首憶惘然 2022-06-23 17:27:39
我想在運行時將元素從 Java GUI 添加到 JSON 數(shù)組但每次在 JSON 文件中創(chuàng)建新數(shù)組時Java GUI 輸入數(shù)據(jù):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      }   ]}但是每次都會創(chuàng)建新數(shù)組,例如:{     "Items":[        {           "Item Type":"TV",         "Quantity":3      }   ]}{     "Items":[        {           "Item Type":"phone",         "Quantity":3      }   ]}
查看完整描述

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ā)生了什么?

  1. 首先,請注意 Java 7 NIO 的用法——推薦的在 java 中處理文件的方法。

  2. jsonParse方法中,我們首先檢查文件是否存在。

    • 如果是 - 然后我們將其讀取到Items描述我們模型的數(shù)據(jù)類 ( ) 中。閱讀部分是在這個庫的底層完成的,只是你的 json 文件的文件應該與數(shù)據(jù)類的字段同名(或用JsonAliasannotation.xml 指定)。

    • 如果沒有 - 那么我們首先創(chuàng)建它并填充初始值。

  3. 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

    }

  ]

}


查看完整回答
反對 回復 2022-06-23
  • 1 回答
  • 0 關注
  • 321 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號