Java-FastJson数据交换测试
1. 使用基本格式:
/**
* 1. 将对象转换成字符串;
* public static String json2str(Object str){}
*
* 2. 将实体对象列表转换成Json字符串
* public static String list2jsonStr(List<?> str){}
*
* 3. 将Json字符串转换成指定类型对象;
* public static <T> T json2obj(String str, Class<T> clazz){}
* public static Object json2obj(String str, Class<T> clazz){}
*
* 4. 将json数组转换成指定类型对象列表;
* public static <T> List<T> jsonArr2List(String str, Class<T> clazz){}
* public static List<?> jsonArr2List(String str, Class<?> clazz){}
*
*/
2. 代码展示: JsonUtil.java
package cn.jensen.eshop.Util;
import cn.jensen.eshop.common.entity.Entity;
import com.alibaba.fastjson2.JSON;
import java.util.ArrayList;
import java.util.List;
public class JsonUtil {
private void usage() {
}
public void start(){
Entity e = new Entity();
e.setDelTime("18:29");
e.setId("20");
System.out.println("**************************");
List<Entity> entityList = new ArrayList<Entity>();
entityList.add(e);
String entitys = json2List(entityList);
System.out.println(entitys);
System.out.println("**************************");
String jsonStr = "{\"delTime\":\"18:39\",\"id\":\"31\",\"isDel\":\"0\"}";
Object obj = json2Obj(jsonStr, Entity.class);
Entity entity = (Entity)obj;
System.out.println("ID: "+entity.getId());
System.out.println("**************************");
String text = "{\"delTime\":\"5:21\",\"id\":\"49\",\"isDel\":\"1\"}";
Entity entityTest = json2GenericType(text, Entity.class);
System.out.println("ID: "+entityTest.getId());
System.out.println("**************************");
String text1 = "[{\"delTime\":\"18:29\",\"id\":\"20\",\"isDel\":\"1\"} ," +
"{\"delTime\":\"5:21\",\"id\":\"49\",\"isDel\":\"1\"}]";
List<Entity> eTest = jsonArray2objArray(text1, Entity.class);
System.out.println("第一个时间: "+ eTest.get(0).getDelTime());
System.out.println("第二个时间: "+ eTest.get(1).getDelTime());
}
public static <T> List<T> jsonArray2objArray(String jsonStr, Class<T> clazz){
return JSON.parseArray(jsonStr, clazz);
}
public static <T> T json2GenericType(String jsonString, Class<T> clazz){
return JSON.parseObject(jsonString,clazz);
}
public static Object json2Obj(String jstr, Class<?> clazz){
Object obj = JSON.parseObject(jstr,clazz);
return obj;
}
public static String json2List(List<?> entity){
return entity2Json(entity);
}
public static String entity2Json(Object entity){
return JSON.toJSONString(entity);
}
public static void main(String[] args) {
JsonUtil test = new JsonUtil();
test.start();
}
}