Json格式化的實現(Jackson、Gson)

1、第一種(Jackson)

  須要用到的jar包:java

  https://pan.baidu.com/s/1wrkUwEoKpmqgmYPQSN-iZg
json

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());
    }

}

 

運行結果:app

第二種方式(Gson):

   須要的jar包:spa

  https://pan.baidu.com/s/1Z7Ah8t45zBKSC6IjuvbzyAcode

 

    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);

    }

 

運行結果:orm

相關文章
相關標籤/搜索