一、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. 对 ThreadLocal 的了解(一)

    Threadlocal ThreadLocal 在我个人理解范围内,主要作用是在同一个线程里面,去共享某个数据给这个线程在不同的阶段去使用. 本次使用范围 在集成 pageOffice 在线 word ...

  2. vue与众不同的学习方式,让她年薪200多万

    学习vue正确思路,是先学vue-cli,再学vue.js单文件引用的用法,这样会在极短时间内撤底撑握vue,如果先学vue.js单文件用法,再去学vue-cli4,可以说是重新学vue,,,,难处大 ...

  3. nodejs实现定时爬取微博热搜

    The summer is coming " 我知道,那些夏天,就像青春一样回不来. - 宋冬野 青春是回不来了,倒是要准备渡过在西安的第三个夏天了. 废话 我发现,自己对 coding 这 ...

  4. 一个页面从输入url到页面加载完成究竟经历了些什么

    本人经参考谢希仁著<计算机网络(第 5版)>.<HTTP权威指南>和网络上关于浏览器渲染原理的介绍,结合自己理解,整理出以下结论,如有不正确或者不完善之处欢迎指正: 当用户在浏 ...

  5. PHP字符串全排列算法

    <?php /** * PHP字符串全排列算法 */ $results = []; $arr = []; function bfs($start) { global $arr; global $ ...

  6. JDK 配置环境变量

    1.配置环境变量 右击 我的电脑 --> 属性 --> 高级系统设置 --> 高级 --> 环境变量 在系统变量里新建 JAVA_HOME 变量,变量值如下 D:\work_s ...

  7. thinkphp历史漏洞

    https://github.com/pochubs/pochubs/blob/master/ThinkPHP.md tp 历史漏洞 路由控制類RCE/think/App.php if (!preg_ ...

  8. 从零开始学习docker之在docker中搭建redis(集群)

    docker搭建redis集群 docker-compose是以多容器的方式启动,非常适合用来启动集群 一.环境准备 云环境:CentOS 7.6 64位 二.安装docker-compose #需要 ...

  9. springboot关于webmvc配置问题记录

    在之前的文章(springboot配置静态资源访问路径)中说过,springboot默认的加载静态资源的地方是在resources目录下的static文件夹下,其实除了resources目录下得sta ...

  10. Oracle创建包

    包: 在公司中,如果业务逻辑比较复杂,需要定义很多过程或者函数.有可能需要定义几十个过程或者函数,这些过程或者函数如果都放到一起,是不是不好管理?我们一般使用包来管理过程或者函数,一个包中可以定义多个 ...