Fastjson Obejct/Map/JSON/String 互转


Introduction to Fastjson

Fastjson is a high-performance and complete JSON library written in Java language. It uses an "assumed ordered fast matching" algorithm to improve the performance of JSON Parse to the extreme. It is currently the fastest JSON library in the Java language. The Fastjson interface is simple and easy to use, and has been widely used in various application scenarios such as cache serialization, protocol interaction, Web output, and Android clients.

Main features:

  • Fast FAST (faster than any other Java-based parser and generator, including jackson)
  • Powerful (support Ordinary JDK classes include any Java Bean Class, Collection, Map, Date or enum)


  • Zero dependencies (no dependencies on any other class libraries except JDK)
  • Open source, using the Apache License 2.0 protocol.
1.2 How to get Fastjson?
https://github.com/alibaba/fastjson

Fastjson Obejct/Map/JSON/String mutual conversion method

at In log parsing and front-end and back-end data transmission and interaction, we often encounter scenarios of mutual conversion and parsing between String and map, json, xml and other formats. Among them, json has basically become the de facto standard data interaction format across languages ​​and front-end and back-end. It should be said that there are a large number of libraries for parsing json in various languages ​​(for an introduction to the specific json format and third-party libraries, please see: http://www.json.org/json-zh.html). For example, python is integrated into the built-in library. , it has become a standard API. Today we are going to talk about how to conveniently use json format in java.

From the above link introduction, we can see that Java has the most three-party json libraries, which can be said to be the rhythm of a hundred flowers blooming and a hundred schools of thought contending. . . However, some libraries have chain dependency problems. You should pay attention when using them. If you don't use maven to manage your dependencies, it will be painful to use, such as json-lib, smart-json, etc. What I would like to recommend below is a json library open sourced by Alibaba engineers: FastJSON. This library is very good in terms of parsing speed and ease of use.


1. Understand fastjson


2. The main uses of fastjson Entrance

Fastjson API entry class is com.alibaba.fastjson.JSON. Common serialization operations can be completed directly through static methods on the JSON class.

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> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray public static final <T> List<T> parseArray(String text, Class<T> 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。

3. Some notes on the class library

SerializeWriter: Equivalent to StringBuffer

JSONArray: Equivalent to List<Object>

JSONObject: Equivalent to Map<String, Object>

There is no real array in JSON deserialization, the essential types are List<Object>

4. Fastjson also has many advanced features

For example, it supports annotations and supports full-type serialization. These are very good features and powerful functions, and are not within the scope of this test.

5. Test code

package lavasoft.stu.json; 

import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.serializer.SerializeConfig; 
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 

import java.util.*; 

/** 
* Created by IntelliJ IDEA. 
* 
* @author leizhimin 11-11-22 上午9:15 
*/ public class Foo { 
	private String vString = "vStringhehhehe"; 
	private char vchar = 'x'; 

	private byte vbyte = 64; 
	private short vshort = 128; 
	private int vint = 65535; 
	private long vlong = 9999999L; 

	private float vfloat = 12.1f; 
	private double vdouble = 22.203d; 

	private boolean vboolean = false; 

//	private Date vdate = new Date(); private Date dddd = new Date(); 
	private Date vDate = new Date(); 
	private Date v_Date = new Date(); 
	private Object vnull = null; 

	private String[] avString = {"aaa", "bbb", "ccc"}; 
	private int[] avint = {1, 2, 3, 4}; 
	private boolean[] avboolean = {true, false, true, true}; 

	private List<String> listString = new ArrayList<String>(); 
	private Map<String, String> map = new HashMap<String, String>(); 

	private Bar bar = new Bar(); 
	private Bar[] avBar = {new Bar(), new Bar()}; 
	private List<Bar> listBar = new ArrayList<Bar>(); 

	{ 
		listString.add("listString1"); 
		listString.add("listString2"); 
		listString.add("listString3"); 

		map.put("x", "s11111x"); 
		map.put("y", "s22222y"); 
		map.put("z", "s33333z"); 

		listBar.add(new Bar()); 
		listBar.add(new Bar()); 
		listBar.add(new Bar()); 
	} 



	public String getvString() { 
		return vString; 
	} 

	public void setvString(String vString) { 
		this.vString = vString; 
	} 

	public char getVchar() { 
		return vchar; 
	} 

	public void setVchar(char vchar) { 
		this.vchar = vchar; 
	} 

	public byte getVbyte() { 
		return vbyte; 
	} 

	public void setVbyte(byte vbyte) { 
		this.vbyte = vbyte; 
	} 

	public short getVshort() { 
		return vshort; 
	} 

	public void setVshort(short vshort) { 
		this.vshort = vshort; 
	} 

	public int getVint() { 
		return vint; 
	} 

	public void setVint(int vint) { 
		this.vint = vint; 
	} 

	public long getVlong() { 
		return vlong; 
	} 

	public void setVlong(long vlong) { 
		this.vlong = vlong; 
	} 

	public float getVfloat() { 
		return vfloat; 
	} 

	public void setVfloat(float vfloat) { 
		this.vfloat = vfloat; 
	} 

	public double getVdouble() { 
		return vdouble; 
	} 

	public void setVdouble(double vdouble) { 
		this.vdouble = vdouble; 
	} 

	public boolean isVboolean() { 
		return vboolean; 
	} 

	public void setVboolean(boolean vboolean) { 
		this.vboolean = vboolean; 
	} 

	public Date getDddd() { 
		return dddd; 
	} 

	public void setDddd(Date dddd) { 
		this.dddd = dddd; 
	} 

	public Date getV_Date() { 
		return v_Date; 
	} 

	public void setV_Date(Date v_Date) { 
		this.v_Date = v_Date; 
	} 

	public Date getvDate() { 
		return vDate; 
	} 

	public void setvDate(Date vDate) { 
		this.vDate = vDate; 
	} 

	public Object getVnull() { 
		return vnull; 
	} 

	public void setVnull(Object vnull) { 
		this.vnull = vnull; 
	} 

	public String[] getAvString() { 
		return avString; 
	} 

	public void setAvString(String[] avString) { 
		this.avString = avString; 
	} 

	public int[] getAvint() { 
		return avint; 
	} 

	public void setAvint(int[] avint) { 
		this.avint = avint; 
	} 

	public boolean[] getAvboolean() { 
		return avboolean; 
	} 

	public void setAvboolean(boolean[] avboolean) { 
		this.avboolean = avboolean; 
	} 

	public List<String> getListString() { 
		return listString; 
	} 

	public void setListString(List<String> listString) { 
		this.listString = listString; 
	} 

	public Map<String, String> getMap() { 
		return map; 
	} 

	public void setMap(Map<String, String> map) { 
		this.map = map; 
	} 

	public Bar getBar() { 
		return bar; 
	} 

	public void setBar(Bar bar) { 
		this.bar = bar; 
	} 

	public Bar[] getAvBar() { 
		return avBar; 
	} 

	public void setAvBar(Bar[] avBar) { 
		this.avBar = avBar; 
	} 

	public List<Bar> getListBar() { 
		return listBar; 
	} 

	public void setListBar(List<Bar> listBar) { 
		this.listBar = listBar; 
	} 
}


package lavasoft.stu.json; 

import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.serializer.SerializeConfig; 
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 

import java.util.Date; 
import java.util.Random; 

/** 
* Created by IntelliJ IDEA. 
* 
* @author leizhimin 11-11-22 上午9:15 
*/ public class Bar { 
	public static SerializeConfig mapping = new SerializeConfig(); 
	private String barName; 
	private int barAge; 
	private Date barDate = new Date(); 
	static { 
		mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); 
	} 
	{ 
		Random r = new Random(); 
		barName = "sss_"+String.valueOf(r.nextFloat()); 
		barAge = r.nextInt(); 
	} 

	public static void main(String[] args) { 
		Object obj = JSON.toJSON(new Bar()); 
		String x1 = JSON.toJSONString(new Bar(), true); 
		System.out.println(x1); 
		String x2 = JSON.toJSONString(new Bar(), mapping); 
		System.out.println(x2); 
	} 

	public String getBarName() { 
		return barName; 
	} 

	public void setBarName(String barName) { 
		this.barName = barName; 
	} 

	public int getBarAge() { 
		return barAge; 
	} 

	public void setBarAge(int barAge) { 
		this.barAge = barAge; 
	} 

	public Date getBarDate() { 
		return barDate; 
	} 

	public void setBarDate(Date barDate) { 
		this.barDate = barDate; 
	} 

	@Override 
	public String toString() { 
		return "Bar{" + 
				"barName='" + barName + '\'' + 
				", barAge=" + barAge + 
				", barDate=" + barDate + 
				'}'; 
	} 
}



package lavasoft.stu.json; 

import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.JSONArray; 
import com.alibaba.fastjson.serializer.SerializeConfig; 
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 

import java.util.*; 

/** 
* Created by 2IntelliJ IDEA. 
* 
* @author leizhimin 11-11-22 上午9:45 
*/ public class Test { 
	private static SerializeConfig mapping = new SerializeConfig(); static { 
		mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 
	} 

	public static void main(String[] args) { 
		Foo f1 = new Foo(); 
		Date date = new Date(); 
		String text = JSON.toJSONString(date, mapping); 
		System.out.println(text); 
		System.out.println(JSON.toJSONString(f1, true)); 
		String x2 =JSON.toJSONString(f1, mapping); 
		System.out.println(x2); 
	} 

	public static void json2List(){ 
		//List -> JSON array 
		List<Bar> barList = new ArrayList<Bar>(); 
		barList.add(new Bar()); 
		barList.add(new Bar()); 
		barList.add(new Bar()); 
		String json= JSON.toJSONString(barList, true); 
		System.out.println(json); 
		//JSON array -> List 
		List<Bar> barList1 = JSON.parseArray(json,Bar.class); 
		for (Bar bar : barList1) { 
			System.out.println(bar.toString()); 
		} 
	} 

	public static void json2Map(){ 
		//Map -> JSON Map<String,Bar> map = new HashMap<String, Bar>(); 
		map.put("a",new Bar()); 
		map.put("b",new Bar()); 
		map.put("c",new Bar()); 
		String json = JSON.toJSONString(map,true); 
		System.out.println(json); 
		//JSON -> Map Map<String,Bar> map1 = (Map<String,Bar>)JSON.parse(json); 
		for (String key : map1.keySet()) { 
			System.out.println(key+":"+map1.get(key)); 
		} 
	} 

	public static void array2JSON(){ 
		String[] arr_String    = {"a","b","c"}; 
		String json_arr_String = JSON.toJSONString(arr_String,true); 
		System.out.println(json_arr_String); 
		JSONArray jsonArray = JSON.parseArray(json_arr_String); 
		for (Object o : jsonArray) { 
			System.out.println(o); 
		} 
		System.out.println(jsonArray); 
	} 
	public static void array2JSON2(){ 
		Bar[] arr_Bar    = {new Bar(),new Bar(),new Bar()}; 
		String json_arr_Bar = JSON.toJSONString(arr_Bar,true); 
		System.out.println(json_arr_Bar); 
		JSONArray jsonArray = JSON.parseArray(json_arr_Bar); 
		for (Object o : jsonArray) { 
			System.out.println(o); 
		} 
		System.out.println(jsonArray); 
	} 

	public static void map2JSON(){ 
		Map map = new HashMap(); 
		map.put("a","aaa"); 
		map.put("b","bbb"); 
		map.put("c","ccc"); 
		String json=JSON.toJSONString(map); 
		System.out.println(json); 
		Map map1 = JSON.parseObject(json); 
		for (Object o : map.entrySet()) { 
			Map.Entry<String,String> entry = (Map.Entry<String,String>)o; 
			System.out.println(entry.getKey()+"--->"+entry.getValue()); 
		} 
	} 
}


illustrate:

SerializeConfig: It is a special configuration for some serialization processes in the serialization process. It is used here to define the date format.

For the full-type serialization process that requires a type, you need to call the JSON.toJSONStringZ() method.

When you need to beautify the output, you need to turn on the serialization beautification switch and set the true parameter in the method.

Output result:
"2011-11-23 23:30:33" { 
  "avBar":[{ 
    "barAge":174398800, 
    "barDate":1322062233062, 
    "barName":"sss_0.62378174" 
  },{ 
    "barAge":38938962, 
    "barDate":1322062233062, 
    "barName":"sss_0.36014742" 
  }], 
  "avString":["aaa","bbb","ccc"], 
  "avboolean":[true,false,true,true], 
  "avint":[1,2,3,4], 
  "bar":{ 
    "barAge":1601495948, 
    "barDate":1322062233062, 
    "barName":"sss_0.46644872" 
  }, 
  "dddd":1322062233046, 
  "listBar":[ 
    { 
      "barAge":-1090113522, 
      "barDate":1322062233062, 
      "barName":"sss_0.83562374" 
    }, 
    { 
      "barAge":478603194, 
      "barDate":1322062233062, 
      "barName":"sss_0.59483266" 
    }, 
    { 
      "barAge":1118357669, 
      "barDate":1322062233062, 
      "barName":"sss_0.9961642" 
    } 
  ], 
  "listString":[ 
    "listString1", 
    "listString2", 
    "listString3" 
  ], 
  "map":{"x":"s11111x","y":"s22222y","z":"s33333z"}, 
  "v_Date":1322062233046, 
  "vboolean":false, 
  "vbyte":64, 
  "vchar":"x", 
  "vdouble":22.203, 
  "vfloat":12.1, 
  "vint":65535, 
  "vlong":9999999, 
  "vshort":128 } 
{"avBar":[{"barAge":174398800,"barDate":"2011-11-23 23:30:33","barName":"sss_0.62378174"},{"barAge":38938962,"barDate":"2011-11-23 23:30:33","barName":"sss_0.36014742"}],"avString":["aaa","bbb","ccc"],"avboolean":[true,false,true,true],"avint":[1,2,3,4],"bar":{"barAge":1601495948,"barDate":"2011-11-23 23:30:33","barName":"sss_0.46644872"},"dddd":"2011-11-23 23:30:33","listBar":[{"barAge":-1090113522,"barDate":"2011-11-23 23:30:33","barName":"sss_0.83562374"},{"barAge":478603194,"barDate":"2011-11-23 23:30:33","barName":"sss_0.59483266"},{"barAge":1118357669,"barDate":"2011-11-23 23:30:33","barName":"sss_0.9961642"}],"listString":["listString1","listString2","listString3"],"map":{"x":"s11111x","y":"s22222y","z":"s33333z"},"v_Date":"2011-11-23 23:30:33","vboolean":false,"vbyte":64,"vchar":"x","vdouble":22.203,"vfloat":12.1,"vint":65535,"vlong":9999999,"vshort":128} 

Process finished with exit code 0

Small test example:

JSONObject json = new JSONObject();
json.put("aa", "11");
json.put("bb", "22");
json.put("cc", "33");String jsonStr = json.toString();
System.out.println(jsonStr);// {"aa":"11","bb":"22","cc":"33"}
	System.out.println(JSONObject.parseObject(jsonStr).get("aa"));// 11String o = "{'area':{'area':'1','pagetype':'home'},'pagetype':'home'}";
System.out.println(((Map) JSONObject.parseObject(o).get("area")).get("area"));// 1String text = JSON.toJSONString(o);Map<String, Object> userMap = 
		JSON.parseObject(o, new TypeReference<Map<String, Object>>() {});
System.out.println(((Map) userMap.get("area")).get("NotExsit"));// nullSystem.out.println(JSON.toJSONString((Map) userMap.get("area")));// {"area":"1","pagetype":"home"}

fastjson passed all tests very well, and its functional performance is No.1. I like its source code The quality is very high, and the author has taken great pains to achieve the best performance, without surpassing other json libraries.

If you need to obtain other related information, you can click: Fastjson object or array to JSON for mutual reference.