java版json解释器及相关代码生成

最近转做前端,但是遇到一个问题就是:

要根据后台得到的json数据进行前端js编程。。。我发现抓取一个json包,然后对着它的格式参数属性来一个一个书写js代码是非常非常痛苦懊恼追悔莫及的。请原谅我用这么多形容词。所以就用业余的匆匆一瞥的时间---时间真的不够,做出了一个草稿形式的app--当然是swing,因为是跨平台---重要的是公司使用的系统除了windows也有linux。

这个程序充满了bug,因为是用Intellij做的,第一次用它来做是swing程序,而且工期太紧了,一天时间做出来,以后可能会翻工。


打包了以后就是这样的:


点击run。bat然后输入下面这个json就可以看到结果了:

{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}



恩,太仓促了,竟然连连树形图片都找不到。。下次要修正。点击生成js代码:



又一个bug。。。。js格式的不是这样的。好吧,有时间慢慢修正。

下面就将核心部分代码贴出来,顺便给出下载的链接。



package EasisTools.UI;

import Easis.Client.AppConfig;
import Easis.Common.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.swing.*;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreeSelectionModel;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-12-21
 * Time: 下午1:43
 * To change this template use File | Settings | File Templates.
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.List;


import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.border.TitledBorder;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
public class JsonStructTree  extends  JPanel  {
    /**
     * 数据源
     * **/
    private JTree  _dbTree;
    private DefaultMutableTreeNode _tableTreeNode;
    private DefaultMutableTreeNode _viewTreeNode;
    private DefaultMutableTreeNode _procTreeNode;
    private DefaultMutableTreeNode _treeRoot;
    private DefaultTreeModel _treeModel;
    private AppConfig appConfig=new AppConfig();

    public void setHandler(TreeClickHandler handler){
        _handler=handler;
    }

    private JSONObject _jsonObj=null;
    private JSONArray _jsonArr=null;


    private TreeClickHandler _handler;
    public JsonStructTree(JSONObject jsonObject,JSONArray jsonArray) {
        _jsonObj=jsonObject;
        _jsonArr=jsonArray;

        setBackground(Color.WHITE);
        setBorder(new TitledBorder(null, "json树形信息", TitledBorder.LEADING, TitledBorder.TOP, null, null));


        setLayout(new BorderLayout(0, 0));

        JScrollPane scrollPane_1 = new JScrollPane();
        add(scrollPane_1, BorderLayout.CENTER);

        JTree dbDetailTree = new JTree();
        _dbTree=dbDetailTree;
        scrollPane_1.setViewportView(dbDetailTree);
        _initTreeList();
    }



    /**
     * 初始化树形结构
     * */
    private void _initTreeList(){
        if(_jsonArr==null&&_jsonObj==null){
            return;
        }


        treeItemInfo _t_tableInfo= new treeItemInfo();
        treeItemInfo _t_viewInfo=new treeItemInfo();
        treeItemInfo _t_procInfo=new treeItemInfo();
        _t_tableInfo.icon="table3.png";
        _t_tableInfo.itemType="";
        _t_tableInfo.name="数据表";

        _t_viewInfo.icon="view_icon.png";
        _t_viewInfo.itemType="";
        _t_viewInfo.name="视图";

        _t_procInfo.icon="database_active.png";
        _t_procInfo.itemType="";
        _t_procInfo.name="存储过程";
        _treeRoot=new DefaultMutableTreeNode();
        treeItemInfo t1=new treeItemInfo();
        t1.icon="sitemap.png";
        t1.name="详细信息";
        t1.itemType="";

        treeItemInfo rootItem=new treeItemInfo();
        if(_jsonObj!=null){

            rootItem.icon="jsonArrayIcon.png";
            rootItem.itemType="jsonObject";
            rootItem.name="json对象";
        }
        else if(_jsonArr!=null){
            rootItem.name="json数组";
            rootItem.itemType="jsonArray";
            rootItem.icon="table163.png";
        }


        _treeRoot.setUserObject(rootItem);
        //--读取下面的json数据,最多三层。
        //--第一层
        if(_jsonObj!=null){
           recursion_setTreeNode(_jsonObj,_treeRoot,0);
        }
        else if(_jsonArr!=null){
            recursion_setTreeNode(_jsonArr,_treeRoot,0);
        }




        //_dbTree=new JTree(new DefaultMutableTreeNode[]{_tableTreeNode,_viewTreeNode,_procTreeNode});
        _treeModel=new DefaultTreeModel(_treeRoot);
        _dbTree.setModel(_treeModel);

        _dbTree.setRootVisible(false);
        //_dbTree.setPreferredSize(new Dimension(150, 25));



        _dbTree.setCellRenderer(new dbDetailCell());
        _dbTree.addMouseListener(new MouseListener() {

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseClicked(MouseEvent e) {
                // TODO Auto-generated method stub

                if(e.getClickCount()>=2){
                    DefaultMutableTreeNode treeNode=(DefaultMutableTreeNode)   _dbTree.getLastSelectedPathComponent();
                    treeItemInfo myitemInfo=  (treeItemInfo) treeNode.getUserObject();

                    if(_handler!=null){

                        _handler.handler(myitemInfo);
                    }
                    else{
                        System.out.println(myitemInfo.name);
                    }

                }

            }
        });

    }
    private int maxLevel=5;



    private void recursion_setTreeNode(Object parentObject,DefaultMutableTreeNode parentNode,int parentLevel){
        if(parentLevel>maxLevel){
            return;
        }
        if(parentObject==null){
            return;
        }
        if(parentObject instanceof  JSONObject){

            JSONObject _obj=(JSONObject) parentObject;

            for(String keyName: _obj.keySet()){
                treeItemInfo _tItem=new treeItemInfo();
                Object cObj=_obj.get(keyName);
                if(cObj instanceof  JSONObject){
                    _tItem.icon="jsonArrayIcon.png";
                    _tItem.name=keyName;
                    _tItem.itemType="jsonObject";
                    DefaultMutableTreeNode _node=new DefaultMutableTreeNode();

                    _node.setUserObject(_tItem);
                    parentNode.add(_node);
                    recursion_setTreeNode(_obj.getJSONObject(keyName),_node,parentLevel+1);
                    continue;
                }
                else if(cObj instanceof  JSONArray){
                    JSONArray _cArr=_obj.getJSONArray(keyName) ;
                    _tItem.icon="table163.png";
                    _tItem.name=keyName;
                    _tItem.itemType="jsonArray";
                    DefaultMutableTreeNode _node=new DefaultMutableTreeNode();

                    _node.setUserObject(_tItem);
                    parentNode.add(_node);
                    recursion_setTreeNode(_obj.getJSONArray(keyName),_node,parentLevel+1);
                    return;
                }
                else{
                    _tItem.icon="function_logo.png";
                    _tItem.name=keyName+"="+StringUtil.cutStr(_obj.getString(keyName),6,"...");
                    _tItem.itemType="jsonAttribute";
                    DefaultMutableTreeNode _node=new DefaultMutableTreeNode();

                    _node.setUserObject(_tItem);
                    parentNode.add(_node);
                    continue;
                }

            }
        }
        else if(parentObject instanceof  JSONArray){

            JSONArray j_arr=(JSONArray) parentObject;
            for(int cindex=0;cindex<j_arr.size();cindex++){
                treeItemInfo _tItem=new treeItemInfo();
                Object objRes=j_arr.get(cindex);
                _tItem.name="["+cindex+"]";
                if(objRes instanceof  JSONObject){
                    _tItem.icon="jsonArrayIcon.png";

                    _tItem.itemType="jsonObject";
                    DefaultMutableTreeNode _node=new DefaultMutableTreeNode();

                    _node.setUserObject(_tItem);
                    parentNode.add(_node);
                    recursion_setTreeNode(objRes,_node,parentLevel+1);
                    continue;
                }
                else if(objRes instanceof  JSONArray){

                    _tItem.icon="table163.png";

                    _tItem.itemType="jsonArray";
                    DefaultMutableTreeNode _node=new DefaultMutableTreeNode();

                    _node.setUserObject(_tItem);
                    parentNode.add(_node);
                    recursion_setTreeNode(objRes,_node,parentLevel+1);
                    return;
                }
                else{
                    _tItem.icon="function_logo.png";
                    _tItem.name+=""+StringUtil.cutStr(objRes.toString(),6,"...");
                    _tItem.itemType="jsonAttribute";
                    DefaultMutableTreeNode _node=new DefaultMutableTreeNode();

                    _node.setUserObject(_tItem);
                    parentNode.add(_node);
                    continue;
                }
            }
        }

    }

    /**
     * 根据某个记录ID绑定树形
     * */
    public void _BindTreeList(int theID){

        _tableTreeNode.removeAllChildren();
        _viewTreeNode.removeAllChildren();
        _procTreeNode.removeAllChildren();

        _dbTree.setModel(_treeModel);
        _dbTree.updateUI();
    }

    /**
     * 针对树形的数据模型
     * */
    public class treeItemInfo{
        public String name;
        public String itemType;
        public String icon;

        public String toString(){
            return this.name;
        }


    }
    /**
     * 自定义tree的显示方式
     * **/
    class dbDetailCell  implements TreeCellRenderer{
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                                      boolean selected, boolean expanded, boolean leaf, int row,
                                                      boolean hasFocus) {
            // TODO Auto-generated method stub
            //DynamicUtilTreeNode dUtilTreeNode=(DynamicUtilTreeNode)value;
            DefaultMutableTreeNode treeNode=(DefaultMutableTreeNode)value;

            Object object=treeNode.getUserObject();

            //setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
            JPanel cPanel=new JPanel();
            cPanel.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));


            if(leaf==false){
                ImageIcon cOpened;
                if(expanded==true){
                    cOpened=appConfig.getResourceIcon("arrow_state_blue_expanded.png", 16	, 16);

                    cPanel.add(new JLabel(cOpened));

                }
                else{
                    cOpened=appConfig.getResourceIcon("arrow_state_blue_right.png", 16	, 16);
                    cPanel.add(new JLabel(cOpened));

                }

            }
            else{
				 /*
				 JLabel lb1=new JLabel();
				 lb1.setPreferredSize(new Dimension(16, 16));
				 cPanel.add(lb1);
				 */
            }

            if(object instanceof treeItemInfo){

                treeItemInfo tItemInfo=(treeItemInfo)object;
                ImageIcon icon= appConfig.getResourceIcon(tItemInfo.icon, 20, 20);
                JLabel l1=new JLabel(icon);
                l1.setText(tItemInfo.name);
                cPanel.add(l1);


            }
            else{

                ImageIcon icon=appConfig.getResourceIcon("stock_unknown.png",20,20);
                JLabel l1=new JLabel(icon);
                l1.setText(value.toString());
                cPanel.add(l1);

            }



            if (selected) {

              //  cPanel.setBackground(Utils.str2color("#90e3f2"));
                //setBackground(Utils.str2color("#90e3f2"));
                //	setBorder(new )
                //setForeground(Color.red);
                //setBackground(tree.getse);
                //setForeground(tree.getSelectionForeground());
            }
            else {
                cPanel.setBackground(tree.getBackground());
                cPanel.setForeground(tree.getForeground());
                //setBackground(tree.getBackground());
                //setForeground(tree.getForeground());
            }
            cPanel.setEnabled(tree.isEnabled());
            cPanel.setFont(tree.getFont());
            cPanel.setOpaque(true);
            // cPanel.setPreferredSize(new Dimension(150, 40));
            return cPanel;
        }}
    public interface TreeClickHandler{

        public void handler(treeItemInfo itemInfo);

    }



}



package EasisTool.Main;

import Easis.Common.StringUtil;
import EasisTools.UI.JsonStructTree;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JSONViewer extends JDialog {
    private JPanel contentPane;
    private JButton buttonOK;
    private JButton buttonCancel;
    private JTextArea txt_json;
    private JComboBox cbox_tplType;
    private JButton btn_GenCode;
    private JScrollPane scroll_tree;
    private JTextArea txt_result;

    public JSONViewer() {
        setContentPane(contentPane);
        setModal(true);
        getRootPane().setDefaultButton(buttonOK);
        init();

        buttonOK.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onOK();
            }
        });

        buttonCancel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        });

// call onCancel() when cross is clicked
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                onCancel();
            }
        });

// call onCancel() on ESCAPE
        contentPane.registerKeyboardAction(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                onCancel();
            }
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
    }
    JSONObject jsonObject=null;
    JSONArray jsonArray=null;
    private void onOK() {
// add your code here
        boolean isArray=false;


        jsonObject=null;
        jsonArray=null;


        try{
        jsonObject= JSON.parseObject(txt_json.getText());
        }
        catch (Exception ed){
        }
        try{
            jsonArray=JSON.parseArray(txt_json.getText());
            isArray=true;
        }
        catch (Exception ed){}

        if(jsonObject==null&&jsonArray==null){
            JOptionPane.showMessageDialog(null,"该字符串不是json数组也不是json对象。");
            return;
        }
        JOptionPane.showMessageDialog(null,"解析成功");
        JsonStructTree jsonStructTree=new JsonStructTree(jsonObject,jsonArray);
        scroll_tree.getViewport().removeAll();
        scroll_tree.getViewport().setView(jsonStructTree);



    }

    private void onCancel() {
// add your code here if necessary
        dispose();
    }

    public static void main(String[] args) {
        JSONViewer dialog = new JSONViewer();
        dialog.pack();
        dialog.setVisible(true);
        System.exit(0);
    }

    private void init(){
        this.setPreferredSize(new Dimension(800,600));
        cbox_tplType.addItem("js形式代码");
        cbox_tplType.addItem("js精简形式代码");
        setEvents();

    }

    private void setEvents(){
        btn_GenCode.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //To change body of implemented methods use File | Settings | File Templates.
                if(cbox_tplType.getSelectedItem()==null){
                    JOptionPane.showMessageDialog(null,"请选择需要生成的模板!");
                    return;
                }
                String selectedTxt=cbox_tplType.getSelectedItem().toString();
                if(selectedTxt.equals("js形式代码")){
                    if(jsonArray==null&&jsonObject==null){
                        JOptionPane.showMessageDialog(null,"您没有进行有效的json解析!");
                        return;
                    }
                    if(jsonObject!=null){

                        txt_result.setText(recursion_getChildNodeString(jsonObject,0,false,0,""));
                        return;
                    }
                    else{
                        txt_result.setText(recursion_getChildNodeString(jsonArray,0,false,0,""));
                        return;
                    }
                }
                else if(selectedTxt.equals("js精简形式代码")){
                    if(jsonArray==null&&jsonObject==null){
                        JOptionPane.showMessageDialog(null,"您没有进行有效的json解析!");
                        return;
                    }
                    if(jsonObject!=null){

                        txt_result.setText(recursion_getChildNodeString(jsonObject,0,true,8,".."));
                        return;
                    }
                    else{
                        txt_result.setText(recursion_getChildNodeString(jsonArray,0,true,8,".."));
                        return;
                    }
                }

            }
        });
    }

    /**
     * @param parentObj 父亲节点。
     * @param parentBlanks 父亲节点的空格数量。
     * @param needLimitLength 是否需要限制值的长度
     * @param limitLength 值的最大长度
     * @param thumbTail 假如限制值长度,那么后面的后缀
     * @return  字符串
     *
     * */
    private String recursion_getChildNodeString(Object parentObj,int parentBlanks,boolean needLimitLength,int limitLength,String thumbTail){
        if(parentObj==null){
            return "";
        }
        String resStr="";
        if(parentObj instanceof JSONObject){
            JSONObject cobj=(JSONObject)parentObj;
             for(String keyName :cobj.keySet()){
                 Object childObj=cobj.get(keyName);
                 if(childObj==null){ continue;}
                 if(childObj instanceof  JSONObject){
                     resStr+=StringUtil.repeatChar(' ',parentBlanks)+keyName+":{\n";
                     resStr+=recursion_getChildNodeString(childObj,parentBlanks+keyName.length()+2,needLimitLength,limitLength,thumbTail);
                     resStr+=StringUtil.repeatChar(' ',parentBlanks+keyName.length()+2)+"};\n";
                 }
                 else if(childObj instanceof  JSONArray){
                     JSONArray objArr=(JSONArray)childObj;
                     resStr+=StringUtil.repeatChar(' ',parentBlanks)+keyName+":[\n";
                     resStr+=recursion_getChildNodeString(objArr,parentBlanks+keyName.length()+2,needLimitLength,limitLength,thumbTail);

                     resStr+=StringUtil.repeatChar(' ',parentBlanks+keyName.length()+2)+"];\n";
                 }
                 else{
                     resStr+=StringUtil.repeatChar(' ',parentBlanks)+keyName+":";
                     String valueStr=childObj.toString();
                     if(needLimitLength){
                         resStr+="\""+ StringUtil.cutStr(valueStr,limitLength,thumbTail)+"\";\n";
                     }
                     else{
                         resStr+="\""+ valueStr+"\";\n";
                     }
                 }

             }
            return resStr;


        }
        else if(parentObj instanceof  JSONArray){
            JSONArray objArr=(JSONArray)parentObj;
           // resStr+=StringUtil.repeatChar(' ',parentBlanks)+"[\n";

            for(int cindex=0;cindex< objArr.size();cindex++){
                Object childObj=objArr.get(cindex);
                if(childObj instanceof  JSONObject){
                    resStr+= recursion_getChildNodeString(objArr.get(cindex),parentBlanks+1,needLimitLength,limitLength,thumbTail);

                }
                else if(childObj instanceof  JSONArray){
                    resStr+= recursion_getChildNodeString(objArr.get(cindex),parentBlanks+1,needLimitLength,limitLength,thumbTail);
                }
                else{
                    String valueStr=childObj.toString();
                    String dotStr=cindex>=objArr.size()-1?"":",";
                    if(needLimitLength){
                        resStr+=StringUtil.repeatChar(' ',parentBlanks+2)+"\""+StringUtil.cutStr(valueStr,limitLength,thumbTail)+"\""+dotStr+"\n";
                    }
                    else{
                        resStr+=StringUtil.repeatChar(' ',parentBlanks+2)+"\""+valueStr+"\""+dotStr+"\n";
                    }

                }
            }
           // resStr+=StringUtil.repeatChar(' ',parentBlanks)+"]\n";
            return resStr;
        }

        else{
            return "";
        }
    }
}


假如想试用的话,就到下面地址,


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值