一、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. 2019-2020-1 20199328《Linux内核原理与分析》第八周作业

    笔记部分 2019/11/4 17:55:22 elf文件代码默认加载到0x8048000,然后是一段首部信息,然后到达程序的真实入口 正常的系统调用会先进入内核态->用户态->系统调用下 ...

  2. Springboot以Tomcat为容器实现http重定向到https的两种方式

    1 简介 本文将介绍在Springboot中如何通过代码实现Http到Https的重定向,本文仅讲解Tomcat作为容器的情况,其它容器将在以后一一道来. 建议阅读之前的相关文章: (1) Sprin ...

  3. 表达式求值--数据结构C语言算法实现

    这篇博客介绍的表达式求值是用C语言实现的,只使用了c++里面的引用. 数据结构课本上的一个例题,但是看起来很简单,实现却遇到了很多问题. 这个题需要构建两个栈,一个用来存储运算符OPTR, 一个用来存 ...

  4. 在线图片资源转换成Base64格式

    function getBase64Image(img) { var canvas = document.createElement("canvas"); canvas.width ...

  5. Git 提交项目命令

    git add .  //添加⽂件到待提交区 git commit -m "注释"  //创建⼀个提交 git push origin   //将修改内容提交

  6. 在独立的 Root 和 Home 硬盘驱动器上安装 Ubuntu

    安装 Linux 系统时,可以有两种不同的方式.第一种方式是在一个超快的固态硬盘上进行安装,这样可以保证迅速开机和高速访问数据.第二种方式是在一个较慢但很强大的普通硬盘驱动器上安装,这样的硬盘转速快并 ...

  7. Semaphores

    信号量和P,V原语的使用可归纳为三种情形: 把信号量视为加锁标志位,其目的是为了实现对某个唯一的共享数据的互斥访问,如各个进程间的某共享变量,数据库中的某个记录. 共享数据的值与信号量本身的值没有直接 ...

  8. A Tile Painting(循环节)

    Ujan has been lazy lately, but now has decided to bring his yard to good shape. First, he decided to ...

  9. RF(页面断言)

    一.RF中断言方式 title should be(断言title与预期指定的title内容相等) Open Browser https://www.baidu.com/ gc Title Shoul ...

  10. 更安全的rm命令,保护重要数据

    更安全的rm命令,保护重要数据 网上流传的安全的rm,几乎都是提供一个rm的"垃圾"回收站,在服务器环境上来说,这实非良方. 我想,提供一个安全的rm去保护一些重要的文件或目录不被 ...