<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency>
import com.google.gson.Gson; import com.google.gson.GsonBuilder;
class JsonHelper { public static Gson gson= new GsonBuilder() .setDateFormat("yyyy-MM-dd HH:mm:ss").create(); public static<T> String toJson(T instance) { if(instance==null) { return ""; } return gson.toJson(instance); } public static<T> T toInstance(String json,String className) { try{ T instance = (T) gson.fromJson(json,Class.forName(className)); return instance; } catch (Exception ex) { System.out.println("序列化失败"); } return null; } public static<T> T toInstance(String json,Class className) { try{ T instance = (T) gson.fromJson(json,className); return instance; } catch (Exception ex) { System.out.println("序列化失败"); } return null; } }
Employee instance = new Employee("Aven", 1000, Calendar.getInstance().getTime()); try{ json=JsonHelper.toJson(instance); System.out.println(json); Employee employee3 = JsonHelper.toInstance(json,"com.ppmoney.test.Employee"); if(employee3!=null) System.out.println(employee3.toString()); } catch (Exception ex) { System.out.println("序列化失败"); }