赞
踩
一、Fastjson简介
Fastjson是一个性能很好的Java语言实现的Json解析器和生成器,由来自阿里巴巴的工程师开发。具有极快的性能,超越任何其他的Java Json Parser。
特点:
json工具对比信息:
jar包:
fastjson-1.2.9.jar
二、Fastjson简单示例
2.1 User实体类
- import java.io.Serializable;
- import java.util.Date;
-
- import com.alibaba.fastjson.annotation.JSONField;
-
-
- public class User implements Serializable{
-
- private int id;
- private String name;
- private int age;
- @JSONField(format="yyyy-MM-dd")
- 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 int getAge() {
- return age;
- }
-
- public void setAge(int age) {
- this.age = age;
- }
-
- public Date getBirthday() {
- return birthday;
- }
-
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
-
- }

2.2 序列化Fastjson测试类
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
-
- import org.junit.Test;
-
- import com.alibaba.fastjson.JSONArray;
- import com.alibaba.fastjson.JSONObject;
- import com.alibaba.fastjson.serializer.PropertyFilter;
- import com.alibaba.fastjson.serializer.SerializeFilter;
- import com.struts2.fileupload.domain.User;
-
-
- public class FastjsonTest {
-
- // 将User对象转换成json
- @Test
- public void test1() {
- User user = new User();
- user.setAge(20);
- user.setBirthday(new Date());
- user.setId(1);
- user.setName("tom");
-
- //第一种,对象转换成json字符串
- //String json = JSONObject.toJSONString(user);
- //System.out.println(json);
-
-
- // 第二种,处理属性在json中是否生成
- SerializeFilter filter = new PropertyFilter() {
-
- @Override
- public boolean apply(Object arg0, String arg1, Object arg2) {
- // System.out.println(arg0); //要转换成json的对象
- // System.out.println(arg1); //属性名称
- // System.out.println(arg2); //属性值
- if (arg1.equals("id")) {
- return false; // 代表不生成在json串中
- }
- return true; // 代表生成在json串中
- }
- };
- // 转换成json
- String json = JSONObject.toJSONString(user, filter);
- System.out.println(json);
- // {"age":20,"birthday":1479455891302,"id":1,"name":"tom"}
- }
-
- // 将List<User>转换成json
- @Test
- public void test2() {
- User u1 = new User();
- u1.setAge(20);
- u1.setBirthday(new Date());
- u1.setId(1);
- u1.setName("tom");
-
- User u2 = new User();
- u2.setAge(20);
- u2.setBirthday(new Date());
- u2.setId(1);
- u2.setName("fox");
- List<User> users = new ArrayList<User>();
- users.add(u1);
- users.add(u2);
-
- String json = JSONArray.toJSONString(users);
- System.out.println(json);
-
- // [{"age":20,"birthday":1479456003742,"id":1,"name":"tom"},{"age":20,"birthday":1479456003742,"id":1,"name":"fox"}]
-
- }
- }

(1) JavaBean
Cla
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。