一、第一种(Jackson)
需要用到的jar包:
https://pan.baidu.com/s/1wrkUwEoKpmqgmYPQSN-iZg
package util; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.nf147.ldl.shop.entity.User; import java.text.SimpleDateFormat; public class JsonUtils { /** * 序列化成json * */ public static String toJson(Object obj) { // 对象映射器 ObjectMapper mapper = new ObjectMapper(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd HH:mm:ss"); mapper.setDateFormat(sdf); String result = null; // 序列化user对象为json字符串 try { result = mapper.writeValueAsString(obj); } catch (JsonProcessingException e) { e.printStackTrace(); } return result; } /** * 反序列化成对象 * */ public static <T> T toObject(String json,Class<T> valueType) { //对象映射器 ObjectMapper mapper=new ObjectMapper(); T result=null; try { result=mapper.readValue(json,valueType); }catch (Exception e) { e.printStackTrace(); } return result; } public static void main(String[] args) { // int u_id, String user_id, String user_pwd, String user_phone, String user_email //创建一个 user 对象 User user = new User(1, "new_user", "123456", "13728729012", "32688099@qq.com"); // 对象转JSON字符串 String user_json = JsonUtils.toJson(user); System.out.println("对象转JSON字符串"+user_json); // JSON字符串转对象 User user1 = JsonUtils.toObject(user_json,User.class); System.out.println("JSON字符串转对象:"+user1.getUser_id()+" "+user1.getUser_pwd()); } }
运行结果:
第二种方式(Gson):
需要的jar包:
https://pan.baidu.com/s/1Z7Ah8t45zBKSC6IjuvbzyA
public static void main(String[] args) { // int u_id, String user_id, String user_pwd, String user_phone, String user_email //创建一个 user 对象 User user = new User(1, "new_user", "123456", "13728729012", "32688099@qq.com"); //对象转JSON String user_str = new Gson().toJson(user); System.out.println("对象转JSON:"+user_str); }
运行结果: