zoukankan      html  css  js  c++  java
  • JSON以及Java转换JSON的方法(前后端经常使用处理方法)

    本文主要讲述例如以下几个内容:

    1、JSON定义以及JSON的特性

    2、怎样在JavaScript中解释JSON格式数据

    3、怎样在Java代码中使用JSON(讲对象转换成JSON对象以及解释JSON字符串)

    一、JSON

       w3c上对JSON有比較具体的介绍。链接http://www.w3school.com.cn/json/index.asp.以下仅讲述重要的几点。

    Json是 JavaScript 对象表示法(JavaScript Object Notation)。是轻量级的文本数据交换格式,具有层级结构(值中存在值), 数据可使用 AJAX 进行传输,独立于语言,具有自我描写叙述性。比XML更小更快更easy解析。

    JSON格式字符串转化为JavaScript对象无需解析器。 JSON 使用 JavaScript 语法。使用JavaScript的eval()函数可生成JavaScript对象。

    以下给出JSON格式的数据,很清晰,无需多做解释,语法请阅读官方文档。

    标准JSON格式数据

    { "firstName":"John" , "lastName":"Doe" }
    标准JSON格式数组数据

    {
    "employees": [
    { "firstName":"John" , "lastName":"Doe" },
    { "firstName":"Anna" , "lastName":"Smith" },
    { "firstName":"Peter" , "lastName":"Jones" }
    ]
    }
    或直接赋值给变量:

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


    二、在JavaScript中解释JSON数据

    JSON 最常见的使用方法之中的一个。是从 web server上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 JavaScript 对象,然后在网页中使用该数据。

    以下直接给出代码演示样例:

    <pre name="code" class="html"><html>
    <head>
    </head>
    <script type="text/javascript">
    function  testjson(){
    
    //Json格式的字符串
    var txt = '{ "employees" : [' +
    '{ "firstName":"Bill" , "lastName":"Gates" },' +
    '{ "firstName":"George" , "lastName":"Bush" },' +
    '{ "firstName":"Thomas" , "lastName":"Carter" } ]}';
    
    //使用eval函数转换成JSON对象
    //eval() 函数使用的是 JavaScript 编译器,可解析 JSON 文本。然后生成 JavaScript 对象。必须把文本包围在括号里,这样才干避免语法错误:
    var obj = eval ("(" + txt 
    	+ ")");
    //通过对象名,然后依据数组下标以及属性名取值
    alert(obj.employees[0].firstName);
    }
    
    </script>
    <body>
    	<a href="" onclick="testjson()">Click me!</a>
    </body>
    </html>
    
    

    直接保存为后缀名为html或htm的文件。用浏览器打开,就能够測试执行结果了。

    三、Java操作JSON

    1、Josn-lib

    JSON-lib这个Java类包用于把bean,map和XML转换成JSON并可以把JSON转回成bean和DynaBean。

    下载地址:http://json-lib.sourceforge.net/

    还要须要的第3方包:

    rg.apache.commons(3.2以上版本号)

    org.apache.oronet.sf.

    ezmorph(ezmorph-1.0.4.jar)

    nu.xom

    以下直接给出代码:

    package com.doyeden.json;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.apache.commons.beanutils.PropertyUtils;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import net.sf.json.xml.XMLSerializer;
    
    public class TestJson {
    	public static void main(String[] args) {
    
    		// 1. List
    		boolean[] booleanArray = new boolean[] { false, false, true, false };
    		JSONArray ja = JSONArray.fromObject(booleanArray);
    		System.err.println(ja);
    
    		List list = new ArrayList();
    		list.add("first");
    		list.add("second");
    		JSONArray jsonArray2 = JSONArray.fromObject(list);
    		System.out.println(jsonArray2);
    
    		JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']");
    		System.out.println(jsonArray3);
    
    		// 2. Map
    		Map map = new HashMap();
    		map.put("name", "json");
    		map.put("bool", Boolean.TRUE);
    		map.put("int", new Integer(1));
    		map.put("arr", new String[] { "a", "b" });
    		map.put("func", "function(i){ return this.arr[i]; }");
    		JSONObject json = JSONObject.fromObject(map);
    		System.out.println(json);
    
    		// 3. JSON Bean
    		JSONObject jsonObject = JSONObject.fromObject(new JsonBean("kevin",
    				"Male"));
    		System.out.println(jsonObject);
    
    		// 4. Json Beans
    		List<JsonBean> lbs = new ArrayList<JsonBean>();
    		JsonBean j1 = new JsonBean("kevin", "Male");
    		JsonBean j2 = new JsonBean("maimai", "Femal");
    		lbs.add(j1);
    		lbs.add(j2);
    		JSONArray ja_beans = JSONArray.fromObject(lbs);
    		System.out.println(ja_beans);
    
    	}
    }
    

    以下的类的get和set方法必须有才干够

    package com.doyeden.json;
    
    public class JsonBean {
    	private String name;
    	private String sex;
    	
    	public JsonBean() {
    		super();
    	}
    	public JsonBean(String name, String sex) {
    		super();
    		this.name = name;
    		this.sex = sex;
    	}
    	public String getName() {
    		return name;
    	}
    	public void setName(String name) {
    		this.name = name;
    	}
    	public String getSex() {
    		return sex;
    	}
    	public void setSex(String sex) {
    		this.sex = sex;
    	}
    	
    }
    

    程序执行结果:

    [false,false,true,false]
    ["first","second"]
    ["json","is","easy"]
    {"arr":["a","b"],"int":1,"name":"json","func":function(i){ return this.arr[i]; },"bool":true}
    {"name":"kevin","sex":"Male"}
    [{"name":"kevin","sex":"Male"},{"name":"maimai","sex":"Femal"}]
    2、 眼下比較流行的fast-json解析 ,很多其它fast-json请自行查阅文档

    阿里巴巴FastJson是一个Json处理工具包,包含“序列化”和“反序列化”两部分,它具备例如以下特征:
    速度最快,測试表明,fastjson具有极快的性能,超越任其它的Java Json parser。

    包含自称最快的JackJson。
    功能强大。全然支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省;无依赖,可以直接执行在

    Java SE 5.0以上版本号;支持Android;开源 (Apache 2.0)

    Fastjson API入口类是com.alibaba.fastjson.JSON,经常使用的序列化操作都能够在JSON类上的静态方法直接完毕。

    public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray 
    public static final JSONObject parseObject(String text)。 // 把JSON文本parse成JSONObject    
    public static final  T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean 
    public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray 
    public static final  List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合 
    public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本 
    public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本 
    public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。

      实例代码:

    (须要导入fastjson的jar包)

    package com.doyeden.json.fastjson;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.alibaba.fastjson.JSON;
    import com.doyeden.json.JsonBean;
    
    public class Test {
    	public static void main(String[] args) {
    		
    		//1 parse bean to json text
    		JsonBean jb=new JsonBean("kevin","Male");
    		System.out.println(JSON.toJSONString(jb));
    		
    		//2 parse list to json array
    		List<JsonBean> ljs=new ArrayList<JsonBean>();
    		JsonBean jb1=new JsonBean("kevin","Male");
    		JsonBean jb2=new JsonBean("maimai","Female");
    		ljs.add(jb2);
    		ljs.add(jb1);
    		System.out.println(JSON.toJSONString(ljs));
    		
    		//3 parse json text to bean
    		String s="{"name":"greg","sex":"Male"}";
    		JSON jO=JSON.parseObject(s);
    		JsonBean j=JSON.toJavaObject(jO, JsonBean.class);
    		System.out.println(j.getName());
    		
    	}
    }
    

    结果:

    {"name":"kevin","sex":"Male"}
    [{"name":"maimai","sex":"Female"},{"name":"kevin","sex":"Male"}]
    greg

    3、其它方式。比如 org-lib等,用法跟上述两种方式很相似。就不做很多其它介绍了。

    个人推荐还是使用fast-json。

    总结:本文讲述了JSON格式数据以及怎样在JavaScript和Java代码中操作JSON格式数据,能够发现。由于JSON自解释性,轻量级。体积小,跨平台等特点。JSON格式数据非常适合作为和后端数据交互的格式。JavaScript本身就能够解释JSON,这样就省去了非常多第三方库。java中,关于讲JSON转换成Java对象以及讲Java对象和对象数组转换成JSON格式数据的类库事实上有非常多,可是眼下来说最快的是fastjson.

  • 相关阅读:
    LeetCode 230. Kth Smallest Element in a BST
    LeetCode 114. Flatten Binary Tree to Linked List
    LeetCode 222. Count Complete Tree Nodes
    LeetCode 129. Sum Root to Leaf Numbers
    LeetCode 113. Path Sum II
    LeetCode 257. Binary Tree Paths
    Java Convert String & Int
    Java Annotations
    LeetCode 236. Lowest Common Ancestor of a Binary Tree
    LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
  • 原文地址:https://www.cnblogs.com/gavanwanggw/p/7101365.html
Copyright © 2011-2022 走看看