基于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);
}
}
}
}