fastJson

一、简介

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

二、特点

    1、高性能(速度最快

    2、功能强大

    3、无依赖

    4、开源(Apache License 2.0

三、实例

    1、demo

       

package com.cxhd.nmsp.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;

/**
 * fastJson实例
 * 
 * @author liyulin
 * @version 1.0 2015年8月26日 下午2:13:48
 */
public class FastJsonDemo {
	public static void main(String[] args) {
		parseObject();
		parseMap();
		parseList();
		
		fromObject();
		fromMap();
		fromList();
	}
	
	/**
	 * 字符串转Object对象
	 */
	public static void parseObject(){
		String jsonObject = "{\"username\":\"admin\",\"password\":\"123456\",\"loginDate\":\"2015-08-26 10:22:23\"}";
		Login login = JSON.parseObject(jsonObject, Login.class);
		
		System.out.println("字符串转对象(Object)==>"+login.getUsername()+":"+login.getPassword()+"\t"+login.getLoginDate());
	}
	
	/**
	 * 字符串转Map对象
	 */
	public static void parseMap(){
		String jsonObject = "{\"username\":\"admin\",\"password\":\"123456\",\"loginDate\":\"2015-08-26 10:22:23\"}";
		Map<String, Object> login = JSON.parseObject(jsonObject, new TypeReference<Map<String, Object>>() {});
		
		System.out.println("字符串转对象(Map)==>"+login.get("username")+":"+login.get("password")+"\t"+login.get("loginDate"));
	}
	
	/**
	 * 字符串转List对象 
	 */
	public static void parseList(){
		StringBuilder jsonList = new StringBuilder();
		jsonList.append("[");
		jsonList.append("{\"username\":\"admin\",\"password\":\"123456\",\"loginDate\":\"2015-08-26 10:22:23\"},");
		jsonList.append("{\"username\":\"admin\",\"password\":\"123456\",\"loginDate\":\"2015-08-26 10:22:23\"}");
		jsonList.append("]");
		List<Login> logins = JSON.parseArray(jsonList.toString(), Login.class);
		
		System.out.println("\n字符串转对象(List)==>");
		for(Login login:logins){
			System.out.println(login.getUsername()+":"+login.getPassword()+"\t"+login.getLoginDate());
		}
	}
	
	/**
	 * Object对象转字符串
	 */
	public static void fromObject(){
		Login login = new Login();
		login.setUsername("admin");
		login.setPassword("123456");
		login.setLoginDate(new Date());
		
		String json = JSON.toJSONStringWithDateFormat(login, "yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteDateUseDateFormat);
		System.out.println("\n对象(Object)转字符串==>"+json);
	}
	
	
	/**
	 * Map对象转字符串
	 */
	public static void fromMap(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", "admin");
		map.put("password", "123456");
		map.put("loginDate", new Date());
		
		String json = JSON.toJSONStringWithDateFormat(map, "yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteDateUseDateFormat);
		System.out.println("\n对象(Map)转字符串==>"+json);
	}
	
	/**
	 * List对象转字符串
	 */
	public static void fromList(){
		List<Login> logins = new ArrayList<Login>();
		for(int i=0; i<4; i++){
			Login login = new Login();
			login.setUsername("admin");
			login.setPassword("123456");
			login.setLoginDate(new Date());
			
			logins.add(login);
		}
		String json = JSON.toJSONStringWithDateFormat(logins, "yyyy-MM-dd hh:mm:ss", SerializerFeature.WriteDateUseDateFormat);
		System.out.println("\n对象(List)转字符串==>"+json);
	}
}

    2、Login.java

       

public class Login{
	private String username;
	private String password;
	private Date loginDate;
	
	public String getUsername() {
		return username;
	}
	
	public void setUsername(String username) {
		this.username = username;
	}
	
	public String getPassword() {
		return password;
	}
	
	public void setPassword(String password) {
		this.password = password;
	}

	public Date getLoginDate() {
		return loginDate;
	}

	public void setLoginDate(Date loginDate) {
		this.loginDate = loginDate;
	}
}

### 使用方法 在FastJson中,对象与JSON的相互转换是基础操作。将对象转换为JSON可使用`JSON.toJSONString(obj)`方法,而将JSON转换为对象则使用`JSON.parseObject(jsonString, User.class)`方法。当JSON中包含Java对象没有的属性时,可通过创建反序列化特性`Feature[] features = {Feature.IgnoreNotMatch}`,并使用`JSON.parseObject(jsonString, User.class, features)`来进行反序列化操作 [^1][^3]。 ### 特性 FastJson具有一些显著特性。在性能方面,相较于Jackson和Gson,FastJson通常性能更高。其API更简单,使用起来较为便捷,并且功能丰富。不过,它也存在一些不足,例如缺乏像Jackson那样丰富的生态系统,设计的优雅程度和稳定性也不如Gson [^1]。 ### 常见问题解决方案 当JSON中包含Java对象没有的属性时,可通过创建反序列化特性并使用相应方法进行反序列化,避免出现异常。如创建`Feature[] features = {Feature.IgnoreNotMatch}`,再使用`JSON.parseObject(jsonString, User.class, features)`进行反序列化 [^1]。 ### 代码示例 ```java import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.parser.Feature; class User { private String name; private int age; // Getters and Setters 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 class FastJsonExample { public static void main(String[] args) { // 创建对象 User user = new User(); user.setName("John"); user.setAge(30); // 对象转JSON String jsonString = JSON.toJSONString(user); System.out.println("Object to JSON: " + jsonString); // JSON转对象 User parsedUser = JSON.parseObject(jsonString, User.class); System.out.println("JSON to Object - Name: " + parsedUser.getName() + ", Age: " + parsedUser.getAge()); // 处理JSON中包含Java对象没有的属性的情况 String jsonWithExtraAttr = "{\"name\":\"John\",\"age\":30,\"extra\":\"value\"}"; Feature[] features = {Feature.IgnoreNotMatch}; User userWithExtra = JSON.parseObject(jsonWithExtraAttr, User.class, features); System.out.println("JSON with extra attr to Object - Name: " + userWithExtra.getName() + ", Age: " + userWithExtra.getAge()); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值