一、Fastjson使用指南W3Cschool文档:
https://www.w3cschool.cn/fastjson/fastjson-quickstart.html
二、Fastjson的maven仓库:
https://mvnrepository.com/artifact/com.alibaba/fastjson
三、常用API:
* import com.alibaba.fastjson.JSON;
* 1、public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
* 2、public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
* 3、public static final T parseObject(String text, Class clazz); // 把JSON文本parse为JavaBean
* 4、public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
* 5、public static final List parseArray(String text, Class clazz); //把JSON文本parse成JavaBean集合
* 6、public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
* 7、public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
* 8、public static final Object toJSON(Object javaObject); 将JavaBean转换为JSONObject或者JSONArray。
四、示例代码:
public static void main(String[] args) {
// 将map转换为json字符串
Map<String, Object> params = new HashMap<String, Object>();
params.put("key1", "value1");
params.put("key2", "value2");
String paramsJsonString = JSON.toJSONString(params);
System.out.println("将map集合转换为json的结果:");
System.out.println(paramsJsonString);
System.out.println();
// 将json字符串转换为map
Map<String, String> respMap = JSON.parseObject(paramsJsonString, new TypeReference<Map<String,String>>(){});
System.out.println("将json转换为map的结果:");
System.out.println(respMap);
System.out.println();
// 将pojo转换为json字符串
Order order = new Order();
order.setName("测试商品");
order.setOrderDate(new Date());
order.setOrderId("0001");
String orderJson = JSON.toJSONString(order);
System.out.println("将POJO转换为json的结果:");
System.out.println(orderJson);
System.out.println();
// 将json字符串转换为POJO
Order parseObject = JSON.parseObject(orderJson, new TypeReference<Order>() {});
System.out.println("将json字符串转换为POJO的结果:");
System.out.println(parseObject);
System.out.println();
// JSONObject
JSONObject jsonObject = new JSONObject();
jsonObject.put("jsonObjectKey1", "jsonObjectValue1");
jsonObject.put("jsonObjectKey2", "jsonObjectValue2");
jsonObject.put("jsonObjectKey3", "jsonObjectValue3");
System.out.println(jsonObject);
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("jsonObject2Key1", "jsonObject2Value1");
jsonObject2.put("jsonObject2Key2", "jsonObject2Value2");
jsonObject2.put("jsonObject2Key3", "jsonObject2Value3");
System.out.println(jsonObject2);
// JSONArray
JSONArray jsonArray = new JSONArray();
jsonArray.add(jsonObject);
jsonArray.add(jsonObject2);
System.out.println(jsonArray);
}