gpt4 book ai didi

java - 如何解析 JSON 数据以绑定(bind)依赖下拉菜单?

转载 作者:行者123 更新时间:2023-11-30 03:20:50 24 4
gpt4 key购买 nike

我有这种格式的 JSON: enter image description here

{"Engineering":{ "Electrical Engineering":{ "ResearchStaff":["research associate","research sciencetist","senior researchsciencetist"], "Non-tenure-track":["research professaor","associateresearch professor","assistant research profesor","clinicalprofesor","clinical associate profesor","clinical assistantprofesor","visiting profesor","visiting associate profesor","visitingassistant profesor"], "Professional Staff":["businessmanager","university research administrator","departmentadministrative assistant"]},

"Computer Science":{ "Research Staff":["research associate","researchsciencetist","senior research sciencetist"], "Tenured":["distinguishedprofessor","professor","associate professor","assistant professor"],"Teaching Faculty":["distinguished professor","professor","associateprofessor","assistant professor"]},

"Computer Engineering":{"Tenured":["distinguishedprofessor","professor","associate professor","assistant professor"],"Teaching Faculty":["lecturer","senior lecturer","adjunct professor"],"Professional Staff":["business manager","university researchadministrator","department administrative assistant"]}

},

"Science":{ "Physics":{ "Research Staff":["researchassociate","research sciencetist","senior research sciencetist"],"Teaching Faculty":["lecturer","senior lecturer","adjunct professor"],"Non-Tenured-Track":["research professaor","associate researchprofessor","assistant research profesor","clinical profesor","clinicalassociate profesor","clinical assistant profesor","visitingprofesor","visiting associate profesor","visiting assistantprofesor"]},

"Chemistry":{ "Tenured":["distinguishedprofessor","professor","associate professor","assistant professor"],"Teaching Faculty":["lecturer","senior lecturer","adjunct professor"],"Non-Tenured-Track":["research professaor","associate researchprofessor","assistant research profesor","clinical profesor","clinicalassociate profesor","clinical assistant profesor","visitingprofesor","visiting associate profesor","visiting assistantprofesor"]}

}

}

这里我想绑定(bind) 4 个下拉菜单,其值如下:学院:{“工程”、“科学”}院系:选择“工程”学院时为{“电气工程”、“计算机科学”},选择“理科”学院时为{“物理”、“化学”}。

此外,在“电气工程”部门内,我们必须将{“研究人员”、“非终身教授”、“专业人员”}绑定(bind)到职位类型下拉列表中,并根据其选择,我需要绑定(bind)职位如果选择“研究人员”职位类型,则标题下拉列表为{“研究助理”、“研究科学家”、“高级研究科学家”},依此类推......

如何解析此静态 JSON 数据并将这些下拉列表分别绑定(bind)到彼此选择的值。

最佳答案

使用 XML 可能更容易做到这一点。让我为您提供使用 XML 的完整解决方案。如果您想尝试使用 JSON 解析器,则必须根据自己的需求调整此解决方案。好的,让我们开始...首先,访问这个网站...

http://www.json.org/java/

...并将以下文件下载到名为:org.json;

的新 java 包中
  • JSONArray.java
  • JSONException.java
  • JSONObject.java
  • JSONString.java
  • JSONStringer.java
  • JSONTokener.java
  • JSONWriter.java
  • XML.java
  • XMLTokener.java

我自己做了这个,并编写了一个小程序将 JSON 字符串转换为 XML:

import org.json.JSONObject;
import org.json.XML;

public class example {

public static void main(String[] args) {
JSONObject json = new JSONObject(getJSONSting() );
String xml = XML.toString(json);
System.out.println(xml);
}

private static final String getJSONSting() {
String data = "{\"Engineering\":{ \"Electrical Engineering\":{ \"Research Staff\":[\"research associate\",\"research sciencetist\",\"senior research sciencetist\"], \"Non-tenure-track\":[\"research professaor\",\"associate research professor\",\"assistant research profesor\",\"clinical profesor\",\"clinical associate profesor\",\"clinical assistant profesor\",\"visiting profesor\",\"visiting associate profesor\",\"visiting assistant profesor\"], \"Professional Staff\":[\"business manager\",\"university research administrator\",\"department administrative assistant\"]},";
data += "\"Computer Science\":{ \"Research Staff\":[\"research associate\",\"research sciencetist\",\"senior research sciencetist\"], \"Tenured\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"], \"Teaching Faculty\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"]}, \"Computer Engineering\":{\"Tenured\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"], \"Teaching Faculty\":[\"lecturer\",\"senior lecturer\",\"adjunct professor\"], \"Professional Staff\":[\"business manager\",\"university research administrator\",\"department administrative assistant\"]}";
data += "},";
data += "\"Science\":{ \"Physics\":{ \"Research Staff\":[\"research associate\",\"research sciencetist\",\"senior research sciencetist\"], \"Teaching Faculty\":[\"lecturer\",\"senior lecturer\",\"adjunct professor\"], \"Non-Tenured-Track\":[\"research professaor\",\"associate research professor\",\"assistant research profesor\",\"clinical profesor\",\"clinical associate profesor\",\"clinical assistant profesor\",\"visiting profesor\",\"visiting associate profesor\",\"visiting assistant profesor\"]},";
data += "\"Chemistry\":{ \"Tenured\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"], \"Teaching Faculty\":[\"lecturer\",\"senior lecturer\",\"adjunct professor\"], \"Non-Tenured-Track\":[\"research professaor\",\"associate research professor\",\"assistant research profesor\",\"clinical profesor\",\"clinical associate profesor\",\"clinical assistant profesor\",\"visiting profesor\",\"visiting associate profesor\",\"visiting assistant profesor\"]}";
data += "}";
data += "}";
return data;
}
}

这里是 XML 格式,您会注意到标签中非法使用空格。我的解决方案中解决了这个问题,因此您可以研究代码以了解我如何纠正问题......

<Engineering>
<Computer Science>
<Tenured>distinguished professor</Tenured>
<Tenured>professor</Tenured>
<Tenured>associate professor</Tenured>
<Tenured>assistant professor</Tenured>
<Research Staff>research associate</Research Staff>
<Research Staff>research sciencetist</Research Staff>
<Research Staff>senior research sciencetist</Research Staff>
<Teaching Faculty>distinguished professor</Teaching Faculty>
<Teaching Faculty>professor</Teaching Faculty>
<Teaching Faculty>associate professor</Teaching Faculty>
<Teaching Faculty>assistant professor</Teaching Faculty>
</Computer Science>
<Electrical Engineering>
<Professional Staff>business manager</Professional Staff>
<Professional Staff>university research administrator</Professional Staff>
<Professional Staff>department administrative assistant</Professional Staff>
<Research Staff>research associate</Research Staff>
<Research Staff>research sciencetist</Research Staff>
<Research Staff>senior research sciencetist</Research Staff>
<Non-tenure-track>research professaor</Non-tenure-track>
<Non-tenure-track>associate research professor</Non-tenure-track>
<Non-tenure-track>assistant research profesor</Non-tenure-track>
<Non-tenure-track>clinical profesor</Non-tenure-track>
<Non-tenure-track>clinical associate profesor</Non-tenure-track>
<Non-tenure-track>clinical assistant profesor</Non-tenure-track>
<Non-tenure-track>visiting profesor</Non-tenure-track>
<Non-tenure-track>visiting associate profesor</Non-tenure-track>
<Non-tenure-track>visiting assistant profesor</Non-tenure-track>
</Electrical Engineering>
<Computer Engineering>
<Tenured>distinguished professor</Tenured>
<Tenured>professor</Tenured>
<Tenured>associate professor</Tenured>
<Tenured>assistant professor</Tenured>
<Professional Staff>business manager</Professional Staff>
<Professional Staff>university research administrator</Professional Staff>
<Professional Staff>department administrative assistant</Professional Staff>
<Teaching Faculty>lecturer</Teaching Faculty>
<Teaching Faculty>senior lecturer</Teaching Faculty>
<Teaching Faculty>adjunct professor</Teaching Faculty>
</Computer Engineering>
</Engineering>
<Science>
<Chemistry>
<Tenured>distinguished professor</Tenured>
<Tenured>professor</Tenured>
<Tenured>associate professor</Tenured>
<Tenured>assistant professor</Tenured>
<Non-Tenured-Track>research professaor</Non-Tenured-Track>
<Non-Tenured-Track>associate research professor</Non-Tenured-Track>
<Non-Tenured-Track>assistant research profesor</Non-Tenured-Track>
<Non-Tenured-Track>clinical profesor</Non-Tenured-Track>
<Non-Tenured-Track>clinical associate profesor</Non-Tenured-Track>
<Non-Tenured-Track>clinical assistant profesor</Non-Tenured-Track>
<Non-Tenured-Track>visiting profesor</Non-Tenured-Track>
<Non-Tenured-Track>visiting associate profesor</Non-Tenured-Track>
<Non-Tenured-Track>visiting assistant profesor</Non-Tenured-Track>
<Teaching Faculty>lecturer</Teaching Faculty>
<Teaching Faculty>senior lecturer</Teaching Faculty>
<Teaching Faculty>adjunct professor</Teaching Faculty>
</Chemistry>
<Physics>
<Non-Tenured-Track>research professaor</Non-Tenured-Track>
<Non-Tenured-Track>associate research professor</Non-Tenured-Track>
<Non-Tenured-Track>assistant research profesor</Non-Tenured-Track>
<Non-Tenured-Track>clinical profesor</Non-Tenured-Track>
<Non-Tenured-Track>clinical associate profesor</Non-Tenured-Track>
<Non-Tenured-Track>clinical assistant profesor</Non-Tenured-Track>
<Non-Tenured-Track>visiting profesor</Non-Tenured-Track>
<Non-Tenured-Track>visiting associate profesor</Non-Tenured-Track>
<Non-Tenured-Track>visiting assistant profesor</Non-Tenured-Track>
<Research Staff>research associate</Research Staff>
<Research Staff>research sciencetist</Research Staff>
<Research Staff>senior research sciencetist</Research Staff>
<Teaching Faculty>lecturer</Teaching Faculty>
<Teaching Faculty>senior lecturer</Teaching Faculty>
<Teaching Faculty>adjunct professor</Teaching Faculty>
</Physics>
</Science>

如果您已经完成了这一步,您可以通过复制以下类来完成项目的其余部分。我已经测试了该解决方案,它似乎工作正常。

这就是看起来完成的样子...

enter image description here

第一个类放置在包org.combobox中:

package org.combobox;

import java.util.ArrayList;
import java.util.List;

import org.w3c.dom.Node;

public class CleanNode {

private String _name;
private List<CleanNode> _nodes = new ArrayList<CleanNode>();

public CleanNode(Node node) {
_name = node.getNodeType() == Node.TEXT_NODE ? node.getNodeValue() : node.getNodeName();
}

private String getName() {
return _name;
}

public CleanNode addChild(Node node) {
CleanNode foundNode = null;
String nodeName = node.getNodeName();
for(CleanNode child : _nodes){
if(child.getName().equals(nodeName)) {
foundNode = child;
break;
}
}
if(foundNode == null) {
foundNode = new CleanNode(node);
_nodes.add(foundNode);
}
return foundNode;
}

public List<CleanNode> getNodes(){
return _nodes;
}

public String toString() {
return _name.replace("_", " ");
}
}

第二个类放置在包org.combobox中:

package org.combobox;

import java.awt.BorderLayout;
import java.awt.Font;
import java.io.IOException;
import java.io.StringReader;
import java.util.Enumeration;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.json.JSONObject;
import org.json.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class ComboBoxChain extends JFrame {
private static final long serialVersionUID = 1L;
private static String _xml;
private Node _root;
private CleanNode _cleanNode;

public ComboBoxChain() throws ParserConfigurationException, SAXException, IOException {
super("ComboBox Chain");
setUIFont (new javax.swing.plaf.FontUIResource("Monospaced",Font.PLAIN,14));
buildXML();
cleanXML();
_root = parse(_xml);
_cleanNode = new CleanNode(_root);
addCleanNodeChildren(_cleanNode, _root);

setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
getContentPane().add(new ComboPanel(_cleanNode), BorderLayout.CENTER);
pack();
setResizable(false);
setLocationRelativeTo(null);
}

private void addCleanNodeChildren(CleanNode cleanNode, Node node) {
if(node.getChildNodes() != null) {
NodeList children = node.getChildNodes();
for(int index = 0; index < children.getLength(); index++){
Node child = children.item(index);
CleanNode cleanChild = cleanNode.addChild(child);
addCleanNodeChildren(cleanChild, child);
}
}
}

protected Node getRootNode() {
return _root;
}

private void cleanXML() {
String xml = _xml;
int beginIndex = -1;
int endIndex = -1;

for(int index = 0; index < _xml.length(); index++) {
if(_xml.charAt(index) == '<') {
beginIndex = index;
}
else if (_xml.charAt(index) == '>') {
endIndex = index;
String originalTag = _xml.substring(beginIndex, endIndex + 1);
String newTag = originalTag;
while(newTag.contains(" ")) {
newTag = newTag.replace(" ", "_");
}
xml = xml.replace(originalTag, newTag);
}
}
_xml = xml;
}

private static final void buildXML() {
String data = "{\"Engineering\":{ \"Electrical Engineering\":{ \"Research Staff\":[\"research associate\",\"research sciencetist\",\"senior research sciencetist\"], \"Non-tenure-track\":[\"research professaor\",\"associate research professor\",\"assistant research profesor\",\"clinical profesor\",\"clinical associate profesor\",\"clinical assistant profesor\",\"visiting profesor\",\"visiting associate profesor\",\"visiting assistant profesor\"], \"Professional Staff\":[\"business manager\",\"university research administrator\",\"department administrative assistant\"]},";
data += "\"Computer Science\":{ \"Research Staff\":[\"research associate\",\"research sciencetist\",\"senior research sciencetist\"], \"Tenured\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"], \"Teaching Faculty\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"]}, \"Computer Engineering\":{\"Tenured\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"], \"Teaching Faculty\":[\"lecturer\",\"senior lecturer\",\"adjunct professor\"], \"Professional Staff\":[\"business manager\",\"university research administrator\",\"department administrative assistant\"]}";
data += "},";
data += "\"Science\":{ \"Physics\":{ \"Research Staff\":[\"research associate\",\"research sciencetist\",\"senior research sciencetist\"], \"Teaching Faculty\":[\"lecturer\",\"senior lecturer\",\"adjunct professor\"], \"Non-Tenured-Track\":[\"research professaor\",\"associate research professor\",\"assistant research profesor\",\"clinical profesor\",\"clinical associate profesor\",\"clinical assistant profesor\",\"visiting profesor\",\"visiting associate profesor\",\"visiting assistant profesor\"]},";
data += "\"Chemistry\":{ \"Tenured\":[\"distinguished professor\",\"professor\",\"associate professor\",\"assistant professor\"], \"Teaching Faculty\":[\"lecturer\",\"senior lecturer\",\"adjunct professor\"], \"Non-Tenured-Track\":[\"research professaor\",\"associate research professor\",\"assistant research profesor\",\"clinical profesor\",\"clinical associate profesor\",\"clinical assistant profesor\",\"visiting profesor\",\"visiting associate profesor\",\"visiting assistant profesor\"]}";
data += "}";
data += "}";

JSONObject json = new JSONObject(data);
_xml = "<Root>" + XML.toString(json) + "</Root>";

System.out.println(_xml);

}

private static final void setUIFont (javax.swing.plaf.FontUIResource f){
Enumeration<Object> keys = UIManager.getDefaults().keys();
while (keys.hasMoreElements()) {
Object key = keys.nextElement();
Object value = UIManager.get (key);
if (value != null && value instanceof javax.swing.plaf.FontUIResource) {
UIManager.put (key, f);
}
}
}

private static final Node parse(String XMLContent) throws ParserConfigurationException, SAXException, IOException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new InputSource(new StringReader(XMLContent)));
return document.getDocumentElement();
}

public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
ComboBoxChain frame;
try {
frame = new ComboBoxChain();
frame.setVisible(true);
}
catch (ParserConfigurationException e) {
e.printStackTrace();
}
catch (SAXException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}

第三个类放在包org.combobox中:

package org.combobox;

import java.awt.BorderLayout;
import java.awt.GridLayout;

import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class ComboPanel extends JPanel {
private static final long serialVersionUID = 1L;

private static final String DEPARTMENT = "Department";
private static final String PROGRAM = "Program";
private static final String FACULTY = "Faculty";
private static final String ACADEMIC_RANK = "Academic Rank";

private JComboBox<CleanNode> _department;
private JComboBox<CleanNode> _program;
private JComboBox<CleanNode> _faculty;
private JComboBox<CleanNode> _rank;

private DependencyLink _rankLink;
private DependencyLink _facultyLink;
private DependencyLink _programLink;
private DependencyLink _departmentLink;

public ComboPanel(CleanNode root) {
super(new BorderLayout());
addCombos(root);
}

private void addCombos(CleanNode root) {
_department = new JComboBox<CleanNode>();
_program = new JComboBox<CleanNode>();
_faculty = new JComboBox<CleanNode>();
_rank = new JComboBox<CleanNode>();

_rankLink = new DependencyLink(_rank, null);
_facultyLink = new DependencyLink(_faculty, _rankLink);
_programLink = new DependencyLink(_program, _facultyLink);
_departmentLink = new DependencyLink(_department, _programLink);
_departmentLink.populate(root);

JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 2));
panel.add(new JLabel(" " + DEPARTMENT + " : "));
panel.add(_department);
panel.add(new JLabel(" " + PROGRAM + " : "));
panel.add(_program);
panel.add(new JLabel(" " + FACULTY + " : "));
panel.add(_faculty);
panel.add(new JLabel(" " + ACADEMIC_RANK + " : "));
panel.add(_rank);

add(panel, BorderLayout.CENTER);
}
}

第四个也是最后一个类位于包org.combobox中:

package org.combobox;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JComboBox;

public class DependencyLink implements ActionListener {

private boolean _isLocked;
private JComboBox<CleanNode>_combo;
private DependencyLink _childLink;
private CleanNode _previousNode;

public DependencyLink(JComboBox<CleanNode>combo, DependencyLink childLink) {
_combo = combo;
_combo.addActionListener(this);
_childLink = childLink;
}

public void actionPerformed(ActionEvent e) {
CleanNode node = (CleanNode)_combo.getSelectedItem();
if(node != _previousNode) {
updateChild();
_previousNode = node;
}
}

private void updateChild() {
if( _childLink != null) {
if(!_isLocked) {
_childLink.populate((CleanNode)_combo.getSelectedItem());
}
}
}

public void populate(CleanNode parentNode) {
_isLocked = true;
_combo.removeAllItems();
if(parentNode != null) {
List<CleanNode> children = parentNode.getNodes();
if(!children.isEmpty()) {
for(CleanNode childNode : children) {
_combo.addItem(childNode);
}
_combo.setSelectedItem(children.get(0));
}
}
_isLocked = false;
updateChild();
}
}

研究代码并根据自己的需要进行调整以实现您自己的实现。

祝你好运,康斯坦丁

关于java - 如何解析 JSON 数据以绑定(bind)依赖下拉菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31372818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com