Swing实现Json小工具

基于Swing 应用程序代码实现,格式化 JSON可视化 JSON(以树形结构显示)、动态组装 JSON 支持数组和嵌套对象,并支持添加和删除节点。最终可以将树形结构转化为 JSON 数据。应用程序还支持清除按钮、拖动大小和缩放。

具体功能点:

  • 格式化 JSON:在输入区域输入 JSON,点击Format JSON按钮,输出区域会显示格式化后的 JSON。
  • 查看 JSON(树形结构):在输入区域输入 JSON,点击View JSON as Tree按钮,右侧树形结构会显示 JSON 解析后的树形结构。
  • 动态组装 JSON:点击Build JSON按钮,输入区域会填充一个示例 JSON。
  • 清除:点击Clear按钮,清空输入和输出区域,并重置树形结构。
  • 追加节点:选择树中的节点,点击Add Node按钮,输入节点名称后,节点会被追加到选中的节点下。
  • 删除节点:选择树中的节点,点击Delete Node按钮,节点会被删除。
  • 创建 JSON:点击Create JSON按钮,会将树形结构转化为 JSON 字符串,并显示在输出区域。

添加Gson依赖

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.9</version>
</dependency>

主框架类,包含JSON编辑器的主要界面

package com.dzy.swing;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 主框架类,包含JSON编辑器的主要界面
 */
public class MainFrame extends JFrame {
    private JTextArea inputArea;
    private JTree jsonTree;
    private DefaultTreeModel treeModel;
    private JTextArea outputArea;
    private JButton formatButton;
    private JButton viewButton;
    private JButton buildButton;
    private JButton clearButton;
    private JButton addButton;
    private JButton deleteButton;
    private JButton createJsonButton;

    public MainFrame() {
        setTitle("JSON Editor");
        setSize(1000, 700);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setMinimumSize(new Dimension(800, 600));

        initComponents();
        setLayout(new BorderLayout());

        // 添加组件到框架
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, new JScrollPane(inputArea), new JScrollPane(jsonTree));
        splitPane.setResizeWeight(0.5);
        add(splitPane, BorderLayout.CENTER);
        add(new JScrollPane(outputArea), BorderLayout.SOUTH);
        add(createButtonPanel(), BorderLayout.NORTH);
    }

    /**
     * 初始化组件
     */
    private void initComponents() {
        inputArea = new JTextArea(20, 40);
        outputArea = new JTextArea(10, 40);
        outputArea.setEditable(false);

        jsonTree = new JTree(new DefaultMutableTreeNode("JSON"));
        treeModel = (DefaultTreeModel) jsonTree.getModel();

        formatButton = new JButton("Format JSON");
        viewButton = new JButton("View JSON as Tree");
        buildButton = new JButton("Build JSON");
        clearButton = new JButton("Clear");
        addButton = new JButton("Add Node");
        deleteButton = new JButton("Delete Node");
        createJsonButton = new JButton("Create JSON");

        // 设置按钮动作监听器
        formatButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String input = inputArea.getText();
                String formattedJson = JsonFormatter.formatJson(input);
                outputArea.setText(formattedJson);
            }
        });

        viewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String input = inputArea.getText();
                DefaultMutableTreeNode root = JsonTreeViewer.parseJsonToTree(input);
                if (root != null) {
                    treeModel.setRoot(root);
                } else {
                    JOptionPane.showMessageDialog(MainFrame.this, "Invalid JSON", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        buildButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String builtJson = JsonBuilder.buildJson();
                inputArea.setText(builtJson);
            }
        });

        clearButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                inputArea.setText("");
                outputArea.setText("");
                treeModel.setRoot(new DefaultMutableTreeNode("JSON"));
            }
        });

        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jsonTree.getLastSelectedPathComponent();
                if (selectedNode != null) {
                    String nodeName = JOptionPane.showInputDialog("Enter node name:");
                    if (nodeName != null) {
                        selectedNode.add(new DefaultMutableTreeNode(nodeName));
                        treeModel.reload();
                    }
                }
            }
        });

        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) jsonTree.getLastSelectedPathComponent();
                if (selectedNode != null && selectedNode.getParent() != null) {
                    treeModel.removeNodeFromParent(selectedNode);
                }
            }
        });

        createJsonButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                DefaultMutableTreeNode root = (DefaultMutableTreeNode) treeModel.getRoot();
                String json = JsonTreeViewer.treeToJson(root);
                outputArea.setText(json);
            }
        });
    }

    /**
     * 创建按钮面板
     * @return JPanel 包含所有操作按钮
     */
    private JPanel createButtonPanel() {
        JPanel panel = new JPanel();
        panel.add(formatButton);
        panel.add(viewButton);
        panel.add(buildButton);
        panel.add(clearButton);
        panel.add(addButton);
        panel.add(deleteButton);
        panel.add(createJsonButton);
        return panel;
    }

    /**
     * 主方法,启动应用程序
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
}

JSON 格式化工具类

package com.dzy.swing;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonSyntaxException;

/**
 * JSON 格式化工具类
 */
public class JsonFormatter {
    /**
     * 格式化JSON字符串
     * @param json 输入的JSON字符串
     * @return 格式化后的JSON字符串
     */
    public static String formatJson(String json) {
        try {
            Gson gson = new GsonBuilder().setPrettyPrinting().create();
            Object jsonObj = gson.fromJson(json, Object.class);
            return gson.toJson(jsonObj);
        } catch (JsonSyntaxException e) {
            return "Invalid JSON: " + e.getMessage();
        }
    }
}

JSON 树形视图工具类

package com.dzy.swing;

import com.google.gson.*;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.Map;
import java.util.Set;

/**
 * JSON 树形视图工具类
 */
public class JsonTreeViewer {
    /**
     * 将JSON字符串解析为树形结构
     * @param json 输入的JSON字符串
     * @return DefaultMutableTreeNode 根节点
     */
    public static DefaultMutableTreeNode parseJsonToTree(String json) {
        try {
            JsonElement jsonElement = JsonParser.parseString(json);
            return buildTreeNode(null, jsonElement);
        } catch (JsonSyntaxException e) {
            return null;
        }
    }

    private static DefaultMutableTreeNode buildTreeNode(String key, JsonElement element) {
        DefaultMutableTreeNode node;
        if (key != null) {
            node = new DefaultMutableTreeNode(key);
        } else {
            node = new DefaultMutableTreeNode("JSON");
        }

        if (element.isJsonObject()) {
            Set<Map.Entry<String, JsonElement>> entrySet = element.getAsJsonObject().entrySet();
            for (Map.Entry<String, JsonElement> entry : entrySet) {
                node.add(buildTreeNode(entry.getKey(), entry.getValue()));
            }
        } else if (element.isJsonArray()) {
            JsonArray array = element.getAsJsonArray();
            for (int i = 0; i < array.size(); i++) {
                node.add(buildTreeNode("[" + i + "]", array.get(i)));
            }
        } else {
            node.add(new DefaultMutableTreeNode(element.toString()));
        }

        return node;
    }

    /**
     * 将树形结构转化为JSON字符串
     * @param root 根节点
     * @return JSON字符串
     */
    public static String treeToJson(DefaultMutableTreeNode root) {
        JsonObject jsonObject = new JsonObject();
        buildJsonFromTree(jsonObject, root);
        return jsonObject.toString();
    }

    private static void buildJsonFromTree(JsonObject jsonObject, DefaultMutableTreeNode node) {
        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i);
            String nodeName = childNode.toString();
            if (childNode.getChildCount() > 0) {
                JsonObject childJsonObject = new JsonObject();
                buildJsonFromTree(childJsonObject, childNode);
                jsonObject.add(nodeName, childJsonObject);
            } else {
                jsonObject.addProperty(nodeName, childNode.toString());
            }
        }
    }
}

JSON 动态组装工具类

package com.dzy.swing;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

/**
 * JSON 动态组装工具类
 */
public class JsonBuilder {
    /**
     * 动态组装一个示例JSON对象
     * @return 组装后的JSON字符串
     */
    public static String buildJson() {
        JsonObject jsonObject = new JsonObject();

        // 创建一个数组
        JsonArray jsonArray = new JsonArray();
        jsonArray.add("element1");
        jsonArray.add("element2");

        // 创建一个嵌套对象
        JsonObject nestedObject = new JsonObject();
        nestedObject.addProperty("key1", "value1");
        nestedObject.addProperty("key2", "value2");

        // 将数组和嵌套对象添加到主对象
        jsonObject.add("array", jsonArray);
        jsonObject.add("nestedObject", nestedObject);

        // 添加一个简单的键值对
        jsonObject.addProperty("simpleKey", "simpleValue");

        return jsonObject.toString();
    }
}

JSON树模型工具类

package com.dzy.swing;

import com.google.gson.JsonObject;

import javax.swing.tree.DefaultMutableTreeNode;

/**
 * JSON树模型工具类
 */
public class JsonTreeModel {
    /**
     * 将树形结构转换为JSON对象
     * @param node 树形结构节点
     * @return JSON对象
     */
    public static JsonObject treeToJson(DefaultMutableTreeNode node) {
        JsonObject jsonObject = new JsonObject();
        buildJsonObject(jsonObject, node);
        return jsonObject;
    }

    private static void buildJsonObject(JsonObject jsonObject, DefaultMutableTreeNode node) {
        for (int i = 0; i < node.getChildCount(); i++) {
            DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i);
            String key = childNode.toString();
            if (childNode.getChildCount() > 0) {
                JsonObject childObject = new JsonObject();
                buildJsonObject(childObject, childNode);
                jsonObject.add(key, childObject);
            } else {
                jsonObject.addProperty(key, key);
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值