zoukankan      html  css  js  c++  java
  • Json格式化的实现(Jackson、Gson)

    一、第一种(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);
    
        }

    运行结果:

  • 相关阅读:
    进军装饰器2/3
    进军装饰器1/3
    购物车
    多级菜单(高效版)
    工资管理系统
    多级菜单(低效版)
    用户登录程序
    Accessibility辅助功能--一念天堂,一念地狱
    使用FragmentTabHost+TabLayout+ViewPager实现双层嵌套Tab
    android性能优化练习:过度绘制
  • 原文地址:https://www.cnblogs.com/ldl326308/p/9600915.html
Copyright © 2011-2022 走看看