【问题标题】:How to parse over JSON data to bind dependent dropdowns?如何解析 JSON 数据以绑定相关下拉列表?
【发布时间】:2015-07-12 21:34:07
【问题描述】:

我有这种格式的 JSON:

{“工程”:{“电气工程”:{“研究 Staff":["研究助理","研究科学家","高级研究人员 科学家”],“非终身职位”:[“研究教授”,“副教授” 研究教授","助理研究教授","临床 教授”、“临床副教授”、“临床助理” 教授”、“客座教授”、“客座副教授”、“客座教授” 助理教授"], "专业职员":["业务 经理","大学研究管理员","部门 行政助理"]},

“计算机科学”:{“研究人员”:[“研究助理”,“研究 sciencetist","高级研究科学家"],"Tenured":["distinguished 教授","教授","副教授","助理教授"], “师资力量”:[“特聘教授”,“教授”,“副教授” 教授","助理教授"]},

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

},

“科学”:{“物理学”:{“研究人员”:[“研究 助理","研究科学家","高级研究科学家"], "师资力量":["讲师","高级讲师","兼职教授"], "Non-Tenured-Track":["研究教授","副研究员 教授”、“助理研究教授”、“临床教授”、“临床 副教授”、“临床助理教授”、“客座” 教授”、“客座副教授”、“客座助理” 教授"]},

“化学”:{“终身”:[“杰出 教授","教授","副教授","助理教授"], "师资力量":["讲师","高级讲师","兼职教授"], "Non-Tenured-Track":["研究教授","副研究员 教授”、“助理研究教授”、“临床教授”、“临床 副教授”、“临床助理教授”、“客座” 教授”、“客座副教授”、“客座助理” 教授”]}

}

}

在这里,我想将 4 个下拉列表的值绑定为: 学院:{“工程”、“科学”} 系:选择“工程”学院时为{“电气工程”、“计算机科学”},选择“理科”学院时为{“物理”、“化学”}。

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

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

【问题讨论】:

  • Google java json parser 你会有一个很好的起点。
  • 谢谢这是最好的答案! @Jean-Paul 但只是如何在客户端解析它并将其绑定到相应的下拉列表,这是我的问题!
  • 您已经标记了JavajQuery。你想用哪种语言解析它?
  • 我喜欢 jQuery,因为我已经使用 Jackson 解析了这个 JSON 数据,现在尝试使用 jQuery 解析这个给定格式的 JSON 对象在客户端页面上绑定!
  • 那你为什么要标记Java?现在康斯坦丁写了一个漂亮的答案,显然,它没有使用首选语言。您不认为这对试图为您提供答案的人具有误导性和不公平吗?请下次尝试正确且明确地标记您的问题。

标签: java jquery json


【解决方案1】:

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

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

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

第一个类放在包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 数据,然后如何解析以绑定到这些下拉列表!
  • 让我把在xml中执行此操作的代码发送给您,我会让您从那里弄清楚...怎么样?给我几分钟完成它
  • 漂亮的答案!非常令人印象深刻 +1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-19
  • 1970-01-01
相关资源
最近更新 更多