您的位置:首页 > Web前端 > JavaScript

JSON-lib的常见用法

2014-10-31 18:53 351 查看

1 JSON的定义

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。
JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。

2 JSON的语法规则

JSON 语法是 JavaScript 对象表示语法的子集。

(1)数据在名称/值对中

(2)数据由逗号分隔

(3)花括号保存对象

(4)方括号保存数组

JSON 值可以是:

(1)数字(整数或浮点数)


(2)字符串(在双引号中)


(3)逻辑值(true 或 false)


(4)数组(在方括号中)


(5)对象(在花括号中)


(6)null

3 JSON-lib

Json-lib可以将Java对象转成json格式的字符串,也可以将Java对象转换成xml格式的文档,同样可以将json字符串转换成Java对象或是将xml字符串转换成Java对象。
源码和Jar包下载地址:http://sourceforge.net/projects/json-lib/files/json-lib/
Maven管理:
<dependency>  
    <groupId>net.sf.json-lib</groupId>  
    <artifactId>json-lib</artifactId>  
    <version>2.4</version>  
    <classifier>jdk15</classifier>  
</dependency>



4 概念解释

(1)JSONArray: is an ordered sequence of values. Its external text form is a string wrapped in square brackets with commas separating the values. The internal form is an object having
get
and
opt
methods for accessing the values by index, and
element
methods for adding or replacing values. The values can be any of these types:
Boolean
,
JSONArray
,
JSONObject
,
Number
,
String
, or the
JSONNull object
.

(2)JSONObject: is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object
having
get
and
opt
methods for accessing the values by name, and
put
methods for adding or replacing values by name. The values can be any of these types:
Boolean
,
JSONArray
,
JSONObject
,
Number
,
String
, or the
JSONNull
object.

5 代码实现

package study.json;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class LearnJson {
	public static void arrayToJson() {
		System.out.println("------------arrayToJson------------------------");
		String[] names={"wahaha","miemie","soga"};
		JSONArray jsonArray=JSONArray.fromObject(names);
		//添加一个新元素
		jsonArray.add("xinjia");
		//在指定index,添加一个新元素
		jsonArray.add(0, 123);
		//删除一个元素
		jsonArray.discard("wahaha");
		//获取指定索引处的值
		System.out.println("指定索引处的值:"+jsonArray.opt(2));
		System.out.println("jsonArray:"+jsonArray);
		//将jsonArray转换为一个collection
		Collection<Object> collection=JSONArray.toCollection(jsonArray);
		System.out.println("转换为collection后输出:"+collection);

	}
	public static void listToJson() {
		System.out.println("-----------------listToJson--------------------------");
		List<Integer> list=new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		list.add(3);
		JSONArray jsonArray=JSONArray.fromObject(list);
		System.out.println(jsonArray);
	}
	public static void setToJson() {
		System.out.println("-----------------setToJson--------------------------");
		Set<Boolean> set=new HashSet<Boolean>();
		set.add(true);
		set.add(false);
		JSONArray jsonArray=JSONArray.fromObject(set);
		System.out.println(jsonArray);
	}
	public static void mapToJson() {
		System.out.println("-----------------mapToJson--------------------------");
		Map<String, Integer> map=new HashMap<String, Integer>();
		map.put("黎明", 23);
		map.put("王浩", 25);
		JSONObject jsonObject=JSONObject.fromObject(map);
		System.out.println(jsonObject);
	}
	public static void beanToJson() {
		System.out.println("-----------------beanToJson--------------------------");
		//Student类必须是public 的,而且必须有setter和getter方法
		Student llq=new Student(1,"llq",24);
		JSONObject jsonObject=JSONObject.fromObject(llq);
		System.out.println(jsonObject);
	}
	public static void jsonToObject() throws Exception{
		System.out.println("-----------------jsonToObject--------------------------");
		String json = "{name:\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
		JSONObject jsonObject=JSONObject.fromObject(json);
		System.out.println(jsonObject);
		//然后可以构造一个bean
		Object bean=JSONObject.toBean(jsonObject);
		System.out.println("获取到的name值:"+PropertyUtils.getProperty(bean, "name"));
		List<Object> arrayList = (List<Object>) JSONArray.toCollection(jsonObject.getJSONArray("array"));
	    for(Object object : arrayList){
	    	System.out.println("list中的:"+object);
	    }
		
	}
	public static void jsonToBean() {
		System.out.println("-----------------jsonToBean--------------------------");
		String stu="{\"age\":24,\"id\":1,\"name\":\"llq\"}";
		JSONObject jsonObject=JSONObject.fromObject(stu);
		//Student必须有无参构造函数
		Object llq=jsonObject.toBean(jsonObject, Student.class);
		System.out.println((Student)llq);
	}
	
	public static void main(String[] args) throws Exception {
		
		arrayToJson();
		listToJson();
		setToJson();
		mapToJson();
		beanToJson();
		jsonToObject();
		jsonToBean();

	}
}


package study.json;

public class Student{
	private int id;
	private String name;
	private int age;
	public Student(int id,String name,int age){
		this.id=id;
		this.name=name;
		this.age=age;
	}
	public  Student() {
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		// TODO Auto-generated method stub
	 return "id:"+id+", name:"+name+", age:"+age;
	}
	
	
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: