fastjson基本操作

一、概述
Fastjson是一个Java语言编写的高性能功能完善的JSON库。它采用一种“假定有序快速匹配”的算法,把JSON Parse的性能提升到极致,是目前Java语言中最快的JSON库。Fastjson接口简单易用,已经被广泛使用在缓存序列化、协议交互、Web输出、Android客户端等多种应用场景。
二、环境搭建

Maven搭建
配置pom.xml文件,在dependencies中加入:
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.6</version>
</dependency>

三、实例

1.实体User.java

package com.xu.demo;

import java.util.Date;

import com.alibaba.fastjson.annotation.JSONField;

/**
 * @FileName User.java
 * @version 1.0
 * 
 */
public class User {

	// 设置别名
	// @JSONField(name = "ID")
	// 设置顺序
	@JSONField(ordinal = 0)
	private int id;

	@JSONField(ordinal = 1)
	private String name;

	@JSONField(ordinal = 2)
	private String password;

	// 设置是否序列化
	// @JSONField(serialize = false)
	// 设置日期格式
	@JSONField(format = "yyyy-MM-dd HH:mm:ss", ordinal = 3)
	private Date birthday;

	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 String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", name=" + name + ", password=" + password
				+ ", birthday=" + birthday + "]";
	}

}

 2. 创建一个FastJsonTest.java测试类

package com.xu.demo;

import java.util.Date;
import java.util.List;

import org.junit.Test;

import com.alibaba.fastjson.JSON;

public class FastJsonTest {

	/**
	 * 将java对象转换成json格式字符
	 */
	@Test
	public void testObjectToJson(){
		User user = new User();
		user.setId(1);
		user.setName("zhangsan");
		user.setPassword("123456");
		user.setBirthday(new Date());
		System.out.println(JSON.toJSONString(user));	//序列化user
		System.out.println(JSON.toJSONStringWithDateFormat(user, "yyyy-MM-dd HH:mm:ss")); //对日期处理
	}
	
	
	/**
	 * 将json格式字符换成java对象转
	 */
	@Test
	public void testJsonToObject(){
		String jsonStr = "{\"birthday\":\"1446777436718\",\"id\":1,\"name\":\"zhangsan\",\"password\":\"123456\"}";
		User user = JSON.parseObject(jsonStr,User.class);
		System.out.println(user);
	}
	
	/**
	 * 将json格式字符换成java集合
	 */
	@Test
	public void testJsonToConnection(){
		String jsonStr = "[{\"id\":1,\"name\":\"zhangsan\",\"password\":\"123456\",\"birthday\":\"2015-11-06 11:31:50\"},"
				+ "{\"id\":2,\"name\":\"lisi\",\"password\":\"123456\",\"birthday\":\"2015-11-06 11:31:50\"}]";
		List<User> userList = JSON.parseArray(jsonStr,User.class);
		for(User user : userList){
			System.out.println(user);
		}
	}
	
}

 

你可能感兴趣的:(json,fastjson,json操作,微风,fastjson基本操作)