fastjson是一个Java语言编写的高性能功能完善的JSON库 支持各种JDK类型。包括基本类型、JavaBean、Collection、Map、Enum、泛型等,fastjson采用独创的算法,将parse的速度提升到极致,超过所有json库,包括曾经号称最快的jackson。以下简单的Map、List<Map>转换json示例:
-
import com.alibaba.fastjson.JSON;
-
import com.alibaba.fastjson.JSONArray;
-
import com.alibaba.fastjson.JSONObject;
-
-
import java.util.ArrayList;
-
import java.util.HashMap;
-
import java.util.Map;
-
-
/***
-
* 利用alibaba的fastjson将数据转化为Json格式
-
*/
-
public class Transform2Json {
-
/** 将Map转换为JsonObject */
-
public static JSONObject map2JsonObject(){
-
-
HashMap<Object, Object> hp = new HashMap<>();
-
hp.put( "lat", 32.7681);
-
hp.put( "lon", "114.1379");
-
hp.put( "header", "iron");
-
hp.put( "request", "post");
-
hp.put( "page", "1");
-
-
String s = JSON.toJSONString(hp);
-
JSONObject jsonObject = JSONObject.parseObject(s);
-
-
return jsonObject;
-
}
-
-
/** 将List<Map>格式数据转换为JsonArray */
-
public static JSONArray list2JsonArray(){
-
-
ArrayList<Map<Object, Object>> maps = new ArrayList<>();
-
HashMap<Object, Object> dataMap = new HashMap<>();
-
HashMap<Object, Object> dataMap1 = new HashMap<>();
-
dataMap.put( "request", "get");
-
dataMap.put( "status", 200);
-
dataMap.put( "header", "git");
-
-
dataMap1.put( "block", "1");
-
maps.add(dataMap);
-
maps.add(dataMap1);
-
-
String s1 = JSON.toJSONString(maps);
-
JSONArray jsonArray = JSONArray.parseArray(s1);
-
-
return jsonArray;
-
}
-
-
public static void main(String[] args) {
-
JSONObject jsonObject = map2JsonObject();
-
JSONArray jsonArray = list2JsonArray();
-
System.out.println( "Map转换JsonObject后:"+jsonObject);
-
System.out.println( "List转换JsonArray后:"+jsonArray);
-
}
-
}
-
-
运行结果如下:
-
Map转换JsonObject后:{ "request": "post", "header": "iron", "lon": "114.1379", "page": "1", "lat": 32.7681}
-
List转换JsonArray后:[{ "request": "get", "header": "git", "status": 200},{ "block": "1"}]
-
-
-
Process finished with exit code 0
-