如何解析JSON数据以绑定依赖的下拉列表? [英] How to parse over JSON data to bind dependent dropdowns?

查看:79
本文介绍了如何解析JSON数据以绑定依赖的下拉列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种格式的JSON:

I have JSON of this format:

{工程":{电气工程":{研究 职员":[研究助理",研究科学家",高级研究" 科学学家"],非终身制":[研究教授",助理 研究教授",助理研究教授",临床" 教授",临床助理教授",临床助手" 教授",来访教授",来访副教授",来访" 助理教授"],专业人员":[业务 经理",大学研究管理员",部门" 行政助理]},

{"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"]},

计算机科学":{研究人员":[研究助理",研究 科学学家",高级研究科学学家"],终身任职":[杰出人士" 教授",教授",副教授",助理教授"]] 教学老师":[杰出教授",教授",副教授" 教授",助理教授"]},

"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"]},

计算机工程":{"Tenured":[杰出 教授",教授",副教授",助理教授"]] 教员":[讲师",高级讲师",兼职教授"], 专业人员":[业务经理",大学研究" 管理员",部门行政助理"]}

"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"]}

},

科学":{物理":{研究人员":[研究 助理",研究科学家",高级研究科学家"], 教员":[讲师",高级讲师",兼职教授"], 非终身制跟踪":[研究教授",相关研究 教授",助理研究员",临床教授",临床" 准教授",临床助理教授",来访" 院长",来访副院长",来访助理" profesor]},

"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"]},

化学":{特质":[杰出 教授",教授",副教授",助理教授"]] 教员":[讲师",高级讲师",兼职教授"], 非终身制跟踪":[研究教授",相关研究 教授",助理研究员",临床教授",临床" 准教授",临床助理教授",来访" 院长",来访副院长",来访助理" 教授]}

"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"]}

}

}

在这里,我想将4个下拉列表绑定为以下值: 学院:{工程",科学"} 部门:选择工程学院"时为{电气工程",计算机科学"},而选择科学"学院时为{物理",化学"}.

Here I want to bind 4 drop-downs with values as: College: {"Engineering", "Science"} Department: {"Electrical Engineering", "Computer Science"} when College "Engineering" is selected and {"Physics", "Chemistry"} when "Science" college is selected.

此外,在电气工程"部门,我们必须将{"Research Staff","Non-tenure-track","Professional Staff"}绑定到Position Type下拉列表中,并且根据其选择,我需要绑定Position如果选择了研究人员"职位类型等,则标题下拉列表为{研究助理",研究科学家",高级研究科学家"}.

Also, within "Electrical Engineering" department we got to bind {"Research Staff", "Non-tenure-track", "Professional Staff"} into Position Type drop-down and based on its selection I need to bind Position Title drop-down as {"research associate","research sciencetist","senior research sciencetist"} if "Research Staff" Position Type is selected and so on....

我该如何解析此静态JSON数据并将这些下拉列表分别绑定到彼此的选定值.

How can I parse through this static JSON data and bind those drop-downs respective to each other's selected value.

推荐答案

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

Might be easier to do this with XML. Let me provide you a full solution using XML. If you want to try your hand using a JSON parser, you will have to adapt this solution for your own needs. OK, let's start ... First, go to this site ...

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

...,然后将以下文件下载到新的Java程序包中:org.json;

... and download the following files into a new java package called : org.json;

  • JSONArray.java
  • JSONException.java
  • JSONObject.java
  • JSONString.java
  • JSONStringer.java
  • JSONTokener.java
  • JSONWriter.java
  • XML.java
  • XMLTokener.java

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

I did this myself and wrote a small program to convert your JSON string to 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格式,您会注意到标记中空格的非法使用.这是我的解决方案中解决的问题,因此您可以研究代码以查看我如何解决此问题...

Here it is in XML format, you will notice the illegal use of spaces in tags. This is addressed in my solution so you may study the code to see how I corrected the problem ...

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

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

If you got this far, you can complete the rest of the project by copying over the following classes. I have tested the solution and it seems to work fine.

这看起来已经完成了...

This is what it looks like completed ...

第一堂课放在包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中:

The fourth and final class is placed in package 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();
  }
}

研究代码并根据自己的喜好对其进行调整.

Study the code and adapt it how you like for your own implementation.

祝你好运, 康斯坦丁

这篇关于如何解析JSON数据以绑定依赖的下拉列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆