一、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;
}

Json转化与ExtJS树(后台处理)的更多相关文章

  1. ASP.NET中使用JSON方便实现前台与后台的数据交换

    ASP.NET中使用JSON方便实现前台与后台的数据交换 发表于2014/9/13 6:47:08  8652人阅读 分类: ASP.NET Jquery extjs 一.前台向后台请求数据 在页面加 ...

  2. jsp中的js嵌入Extjs与后台action交互

    近期做前台须要和后台交互数据,直接使用js一直没实现.最后使用extjs实现了,extjs代码直接嵌入到jsp的js代码中就可以(0跟jsp里使用extjs一样,须要载入extjs的几个文件) < ...

  3. 树后台数据存储(採用webmethod)

    树后台数据存储 关于后台数据存储将集中在此篇解说 /* *作者:方浩然 *日期:2015-05-26 *版本号:1.0 */ using System; using System.Collection ...

  4. at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:142) :json转化“$ref 循环引用”的问题

    原因: entity实体中存在@OneToMany,@ManyToOne注解,在转化json是产生了循环引用 报的错误 解决方法: springmvc @ResponseBody 默认的json转化用 ...

  5. BNU 28887——A Simple Tree Problem——————【将多子树转化成线段树+区间更新】

    A Simple Tree Problem Time Limit: 3000ms Memory Limit: 65536KB This problem will be judged on ZJU. O ...

  6. 1.4.1 对象与JSON转化 1.4.2 JSON与List集合转化 1.1.1 获取json中的属性 day10-05

    1.1.1 对象与JSON转化 @Test public void toJSON() throws IOException{ Jedis jedis = new Jedis("192.168 ...

  7. Extjs treePanel 后台Json的两种构建方法

    public string json = ""; public string QueryMenuTreeJson(string ParentID, string userId) { ...

  8. ExtJS与后台Java交互

    参考博客:http://blog.csdn.net/wanghuan203/article/details/8125970 开发环境:Eclipse + Tomcat + ExtJS6.0 工程目录结 ...

  9. 菜鸟笔记:node.js+mysql中将JSON数据构建为树(递归制作树状菜单数据接口)

    初学Web端开发,今天是第一次将所学做随笔记录,肯定存在多处欠妥,望大家海涵:若有不足,望大家批评指正. 进实验室后分配到的第一个项目,需要制作一个不确定层级树形菜单的数据接口,对于从来没实战编过程的 ...

随机推荐

  1. tx-Lcn 分布式事务

    测试内容 SpringCloud 微服务,有两个服务,从资料服务调度到文件服务,优先在文件服务那边 save 文件后,然后拿到 fileId 存储在资料服务中.两者之间的调用使用 feign.这期间涉 ...

  2. java中ThreadLocal的使用

    文章目录 在Map中存储用户数据 在ThreadLocal中存储用户数据 java中ThreadLocal的使用 ThreadLocal主要用来为当前线程存储数据,这个数据只有当前线程可以访问. 在定 ...

  3. java并发中的Synchronized关键词

    文章目录 为什么要同步 Synchronized关键词 Synchronized Instance Methods Synchronized Static Methods Synchronized B ...

  4. Springboot中,Tomcat启动war包的流程

    将一个SpringBoot项目,打成war包 <!-- 1. 修改POM依赖 --> <dependency> <groupId>org.springframewo ...

  5. 【Linux网络基础】网络子网划分基础知识(IP地址,子网)

    一. IP地址分类与子网划分基础 1. 什么是IP地址? 常见的ip地址版本为ipv4, ipv6 32位 4 * 8=32位. 32位二进制数字序列组成的数字序列   点分十进制 采用点将32位数字 ...

  6. 从零开始创建CocoaPods私有库

    为什么要创建CocoaPods私有库? 避免重复的造轮子 节约时间,方便管理自己的代码 精益求精 创建CocoaPods私有库 1.创建私有仓库工程 执行命令pod lib create SmartB ...

  7. iOS9.2.1 App从AppStore上下载闪退问题

    首先这是小编的第一篇文章,我是一名做iOS开发的小白,出于爱好会更新发表些相关的技术文章,偶尔也会发些视频.恳请大家不要去嘲笑一个努力的人,要是做的不好请多多评论,反正我也不改. 好了!敲黑板!!说正 ...

  8. pytho xlrd简介

    xlrd:是什么? xlrd是python的一个模块,主要用来对Excel进行读的操作,相对应的,xlwd就是对Excel进行写的模块了. xlrd中有哪些方法可以用呢? 1.打开Excel文件读取数 ...

  9. G - Queue HDU - 5493 线段树+二分

    G - Queue HDU - 5493 题目大意:给你n个人的身高和这个人前面或者后面有多少个比他高的人,让你还原这个序列,按字典序输出. 题解: 首先按高度排序. 设每个人在其前面有k个人,设比这 ...

  10. 【学习笔记】Shell-1 变量:命名规范、变量赋值/取值/取消、局部变量/全局变量、预设环境变量

    1.Shell变量 从变量的实质上来说,变量名是指向一片用于存储数据的内存空间. Shell变量是一种弱类型的变量,即声明变量时不需要指定其变量类型,也不需求遵循“先声明再使用”的规定,想用即可用. ...