Json转化与ExtJS树(后台处理)

一、JSON对格式化数据的操作:

1.导入依赖包:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

2.Map转化为JSON数组:

//声明一个Hash对象并添加数据
Map params =  new HashMap();

params.put("username", username);
params.put("user_json", user);

//声明JSONArray对象并输入JSON字符串
JSONArray array = JSONArray.fromObject(params);
put.println(array.toString());

3.String 转换为JSON对象

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

//别忘了添加上JSON包哦!
public class StringToJSON {
    public static void main(String[] args) throws JSONException{
        
        System.out.println("abc");
        //定义JSON字符串
        String jsonStr = "{\"id\": 2," + 
                " \"title\": \"json title\", " + 
                "\"config\": {" +
                    "\"width\": 34," +
                    "\"height\": 35," +
                "}, \"data\": [" +
                    "\"JAVA\", \"JavaScript\", \"PHP\"" +
                "]}";
        
        //转换成为JSONObject对象
        JSONObject jsonObj = new JSONObject(jsonStr);
        
        //从JSONObject对象中获取数据
        JavaBean bean = new JavaBean();
        
        //根据属性名称获取int型数据;
        bean.setId(jsonObj.getInt("id"));     
        
        //根据属性名获取String数据;
        bean.setTitle(jsonObj.getString("title")); 
        
        //根据属性名获取JSONObject类
        JSONObject config = jsonObj.getJSONObject("config");
        bean.setWidth(config.getInt("width"));
        bean.setHeight(config.getInt("height"));
        
        //根据属性名获取JSONArray数组
        JSONArray data = jsonObj.getJSONArray("data");
        for(int index = 0, length = data.length(); index < length; index++) {
            //这里在org.json.JSONArray对象中居然没有找到toArray方法,求各位网友给出解决办法啊!
//            bean.setLanguages(String[]);
        }        
    }
}

class JavaBean{
    private int id ;
    private String title;
    private int width;
    private int height;
    private String[] languages;

        //这里省略了设置器和访问器
}

4.JSON转化为String

public static void main(String[] args) throws JSONException {
        
        //创建JSONObject对象
        JSONObject json = new JSONObject();
        
        //向json中添加数据
        json.put("username", "wanglihong");
        json.put("height", 12.5);
        json.put("age", 24);
        
        //创建JSONArray数组,并将json添加到数组
        JSONArray array = new JSONArray();
        array.put(json);
        
        //转换为字符串
        String jsonStr = array.toString();
        
        System.out.println(jsonStr);
    }

5.集合转换为JSON

public static void main(String[] args)throws JSONException{
        //初始化ArrayList集合并添加数据
        List<String> list = new ArrayList<String>();
        list.add("username");
        list.add("age");
        list.add("sex");
        
        //初始化HashMap集合并添加数组
        Map map = new HashMap();
        map.put("bookname", "CSS3实战");
        map.put("price", 69.0);
        
        //初始化JSONArray对象,并添加数据
        JSONArray array = new JSONArray();
        array.put(list);
        array.put(map);
        
        //生成的JSON字符串为:[["username","age","sex"],{"price":69,"bookname":"CSS3实战"}]
    }

6.数据读写:

读数据:

import java.io.FileNotFoundException;
import java.io.FileReader;

import com.google.gson.JsonArray;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;

public class Json_read {

    public static void main(String[] args) {
        
        try {
            JsonParser parser = new JsonParser();
            JsonObject object = (JsonObject) parser.parse(new FileReader("test.json"));
            System.out.println("cat="+object.get("cat").getAsString());
            System.out.println("pop="+object.get("pop").getAsBoolean());
            
            JsonArray array = object.get("languages").getAsJsonArray();
            for(int i=0;i<array.size();i++){
                System.out.println("--------");
                JsonObject subObject = array.get(i).getAsJsonObject();
                System.out.println("id="+subObject.get("id").getAsInt());
                System.out.println("name="+subObject.get("name").getAsString());
                System.out.println("ide="+subObject.get("ide").getAsString());
                
            }
            
        } catch (JsonIOException e) {
            e.printStackTrace();
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

}

写数据:

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class Json_Write {

    public static void main(String[] args) {
        JsonObject object = new JsonObject();//整体jsonobject容器
        object.addProperty("cat", "it");
        
        JsonArray array = new JsonArray();
        
        JsonObject lan1 = new JsonObject();
        lan1.addProperty("id", 1);
        lan1.addProperty("name", "java");
        lan1.addProperty("ide", "eclipse");
        array.add(lan1);
        
        JsonObject lan2 = new JsonObject();
        lan2.addProperty("id", 2);
        lan2.addProperty("name", "switf");
        lan2.addProperty("ide", "XCode");
        array.add(lan2);
        
        JsonObject lan3 = new JsonObject();
        lan3.addProperty("id", 3);
        lan3.addProperty("name", "c#");
        lan3.addProperty("ide", "visual studio");
        array.add(lan3);
        
        object.add("languages", array);
        
        object.addProperty("pop", true);
        
        System.out.println(object.toString());
        
    }

}

testJson:

{
   "cat":"it",
   "languages":[
      {"id":1,"ide":"Eclipse","name":"Java"},
      {"id":2,"ide":"XCode","name":"Swift"},
      {"id":3,"ide":"Visual studio","name":"c#"}
   ],
   "pop":true
}

 

二、将字符串转换为ExtJS树:

1.符合ExtJS树结果的转义json:

[{\"id\":\"5\",\"parentId\":\"1\",\"nodeCode\":\"ITOB\",\"text\":\"IT对象\",\"nodeNote\":\"null\",\"children\":[{\"id\":\"488\",\"parentId\":\"5\",\"nodeCode\":\"APP\",\"text\":\"应用资源\",\"nodeNote\":\"null\",\"leaf\":\"true\"},{\"id\":\"491\",\"parentId\":\"5\",\"nodeCode\":\"USER\",\"text\":\"用户\",\"nodeNote\":\"null\",\"leaf\":\"true\"},{\"id\":\"490\",\"parentId\":\"5\",\"nodeCode\":\"DATA\",\"text\":\"数据资源\",\"nodeNote\":\"null\",\"leaf\":\"true\"},{\"id\":\"487\",\"parentId\":\"5\",\"nodeCode\":\"HDWE\",\"text\":\"硬件资源\",\"nodeNote\":\"null\",\"leaf\":\"true\"},{\"id\":\"489\",\"parentId\":\"5\",\"nodeCode\":\"SRV\",\"text\":\"服务资源\",\"nodeNote\":\"null\",\"leaf\":\"true\"},{\"id\":\"492\",\"parentId\":\"5\",\"nodeCode\":\"ROLE\",\"text\":\"角色\",\"nodeNote\":\"null\",\"leaf\":\"true\"}]}]

2.TreeNode实体:



import java.util.*;

public class TreeNode
{
    private String id;
    private String text;
    private String parentId;
    private String iconCls;
    private String cls;
    private String uiProvider;
    private Boolean checkbox;
    private Boolean checked;
    private Boolean leaf;
    private Boolean expanded;
    private List<TreeNode> children;
    private Map<String, String> data;
    
    public TreeNode() {
        this.id = "";
        this.text = "";
        this.parentId = "";
        this.iconCls = "";
        this.cls = "forum";
        this.uiProvider = "";
        this.checkbox = false;
        this.checked = false;
        this.leaf = true;
        this.expanded = false;
        this.children = new ArrayList<TreeNode>();
        this.data = new HashMap<String, String>();
    }
    
    public String getId() {
        return this.id;
    }
    
    public void setId(final String id) {
        this.id = id;
    }
    
    public String getText() {
        return this.text;
    }
    
    public void setText(final String text) {
        this.text = text;
    }
    
    public String getParentId() {
        return this.parentId;
    }
    
    public void setParentId(final String parentId) {
        this.parentId = parentId;
    }
    
    public String getIconCls() {
        return this.iconCls;
    }
    
    public void setIconCls(final String iconCls) {
        this.iconCls = iconCls;
    }
    
    public String getCls() {
        return this.cls;
    }
    
    public void setCls(final String cls) {
        this.cls = cls;
    }
    
    public String getUiProvider() {
        return this.uiProvider;
    }
    
    public void setUiProvider(final String uiProvider) {
        this.uiProvider = uiProvider;
    }
    
    public Boolean getCheckbox() {
        return this.checkbox;
    }
    
    public void setCheckbox(final Boolean checkbox) {
        this.checkbox = checkbox;
    }
    
    public Boolean getChecked() {
        return this.checked;
    }
    
    public void setChecked(final Boolean checked) {
        this.checked = checked;
    }
    
    public Boolean getLeaf() {
        return this.leaf;
    }
    
    public void setLeaf(final Boolean leaf) {
        this.leaf = leaf;
    }
    
    public Boolean getExpanded() {
        return this.expanded;
    }
    
    public void setExpanded(final Boolean expanded) {
        this.expanded = expanded;
    }
    
    public List<TreeNode> getChildren() {
        return this.children;
    }
    
    public void setChildren(final List<TreeNode> children) {
        this.children = children;
    }
    
    public Map<String, String> getData() {
        return this.data;
    }
    
    public void setData(final Map<String, String> data) {
        this.data = data;
    }
}

3.ExtJS格式解析:(参考:https://zyjustin9.iteye.com/blog/2170196

id:"id"                     //节点ID  
text:"节点文本"             //节点显示的文本  
cls:"folder/file"           //节点显示的样式:文件夹或文件  
pid:"id"                    //父节点的ID  
leaf:true                   //是否是叶子节点  
expanded:fasle              //是否展开,默认不展开  
checked:false               //true则在text前有个选中的复选框,false则text前有个未选中的复选框,默认没有任何框框  
href:"http://www.123.com"   //节点的链接地址  
hrefTarget:"mainFrame"      //打开节点链接地址默认为blank,可以设置为iframe名称id,则在iframe中打开  
qtip:"提示"               //提示信息,不过要有Ext.QuickTips.init();  
singleClickExpand:true      //用单击文本展开,默认为双击  

4.代码转化 (可以去参考https://blog.csdn.net/cronousgt/article/details/53502999

         //初始化数据
        List<TreeNode> treeList =new ArrayList<TreeNode>();
		TreeNode tns =new TreeNode();
		tns.setId("root");
		tns.setText("质量检测");
		tns.setParentId(null);
		treeList.add(tns);
		Map<String,String> map =new HashMap<>();
		Recursion r = new Recursion();
		JSONObject ob=null;
		JSONArray a=null;
		JSONObject cc =null;
		try {
			ob =new JSONObject(aa);//将String数据转换为可以操作的json数据
			a =ob.getJSONArray("profiles");//将子Json数组
			for(int i=0;i<a.length();i++){//获取json数组中的数据
				cc =new JSONObject(a.get(i).toString());
				tns =new TreeNode();
				tns.setId(cc.getString("key").toString());//id
				tns.setText(cc.getString("name").toString());//text
				tns.setParentId(cc.getString("languageName").toString());//parentId,父节点
				map.put(cc.getString("languageName").toString(), cc.getString("languageName").toString());
				treeList.add(tns);
			}
			for(String v : map.values()){
				tns =new TreeNode();
				tns.setId(v);//id
				tns.setText(v);//text
				tns.setParentId("root");//parentId,父节点
				treeList.add(tns);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

将List<T>中的数据组装成ExtJS树:

//利用双重循环形成一棵树。
	List<TreeNode> rootTree = new ArrayList<TreeNode>();
	for(TreeNode treeNode : treeList){
		//判断是否为root跟节点,是就加入rootTree
		if(treeNode.getParentId()==null){
			rootTree.add(treeNode);
		}
		for(TreeNode t : treeList){
			if(t.getParentId()!=null&&t.getParentId().equals(treeNode.getId())){
				if(treeNode.getChildren() == null){
					List<TreeNode> myChildrens = new ArrayList<TreeNode>();
					myChildrens.add(t);
					treeNode.setChildren(myChildrens);
				}else{
					treeNode.getChildren().add(t);
				}
				treeNode.setLeaf(false);
				}
			}
		}
		return rootTree;
	}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值