• 转json工具类


    package com.csf.practicetest.json;
    
    
    import com.csf.practicetest.json.entity.RespObj;
    import com.csf.practicetest.json.entity.XcfRpoertAnalyseSimplify;
    
    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    /**
     * 测试类
     */
    public class JsonTest {
    
        public static void main2(String[] args) {
            Map<String, Object> obj = new HashMap<String, Object>();
            obj.put("k1", "k1v");
            obj.put("k2", 2);
            try {
                obj.put("k3", JsonUtil.parseDate("2013-01-02"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println(JsonUtil.toJson(obj));
            System.out.println(JsonUtil.toJson(obj, "yyyy-MM-dd"));
            System.out.println(JsonUtil.toJson(obj));
    
        }
    
        /**
         * {"code":"200","type":"SUCCESS","message":[{"name":"2011-2015年公司海外营业收入(单位:亿元)","url":"report/AP201610270029422533/img-0140.png","id":"AP201607260016744779","dt":"20170108010655","p":null},{"name":"2011-2015年公司海外营业收入(单位:亿元)","url":"report/AP201610270029422533/img-0140.png","id":"AP201607260016744779","dt":"20170108010655","p":null}]}
         * JavaBean 转为json字符串 
         *
         * @param args
         */
        public static void main(String[] args) {
            Object message = getMessage();
    
            RespObj res = new RespObj();
            res.setCode("200");
            res.setType("SUCCESS");
            res.setMessage(message);
    
            System.out.println(JsonUtil.toJson(res));
        }
    
        public static Object getMessage() {
            List<XcfRpoertAnalyseSimplify> list = new ArrayList<XcfRpoertAnalyseSimplify>();
            XcfRpoertAnalyseSimplify entity = new XcfRpoertAnalyseSimplify();
            entity.setId("AP201605190014926455");
            entity.setDt("20170108003552");
            entity.setName("公司近年净利润及增长情况");
            entity.setUrl("report/AP201605190014926455/img-0139.png");
            list.add(entity);
    
            entity.setId("AP201607260016744779");
            entity.setDt("20170108010655");
            entity.setName("2011-2015年公司海外营业收入(单位:亿元)");
            entity.setUrl("report/AP201610270029422533/img-0140.png");
            list.add(entity);
            return list;
        }
    
    }
    
    
    -----------------------------------------------------------------------------------------------------------------------
    package com.csf.practicetest.json;
    
    import com.google.gson.*;
    import com.google.gson.reflect.TypeToken;
    import org.apache.commons.lang.StringUtils;
    import org.apache.log4j.Logger;
    
    import java.lang.reflect.Type;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    /**
     * json 转换工具  由对象转化为json
     *
     *  <!--json使用的包-->
     *  <dependency>
     *      <groupId>com.google.code.gson</groupId>
     *       <artifactId>gson</artifactId>
     *      <version>2.3.1</version>
     *      <scope>compile</scope>
     *  </dependency>
    
     *  <dependency>
     *      <groupId>commons-lang</groupId>
     *      <artifactId>commons-lang</artifactId>
     *      <version>2.6</version>
     *  </dependency>
     */
    public class JsonUtil {
    
        private static final Logger logger = Logger.getLogger("JsonUtil.class");
    
        public static final String EMPTY_JSON = "{}";
        public static final String EMPTY_JSON_ARRAY = "[]";
    
        private JsonUtil() {
        }
    
        private static final GsonBuilder builder = new GsonBuilder();
    
        private static final Gson gson = builder.serializeNulls().serializeSpecialFloatingPointValues()
                .registerTypeAdapter(Date.class, new JsonUtil().new JsonDateDeserializer()).create();
    
        /**
         * by default,this method allows serialize null-value properties
         */
        public static String toJson(Object src) {
            if (src == null) {
                return EMPTY_JSON;
            }
            return gson.toJson(src);
        }
    
        /**
         * default is medium : Mar 8, 2013 12:00:00 AM
         * @param obj
         * @param dateFormat
         *            Note that this pattern must abide by the convention provided
         *            by SimpleDateFormat class.
         */
        public static String toJson(Object obj, String dateFormat) {
            if (obj == null) {
                return EMPTY_JSON;
            } else if (StringUtils.isBlank(dateFormat)) {
                return gson.toJson(obj);
            }
    
            try {
                return builder.setDateFormat(dateFormat).serializeSpecialFloatingPointValues().create().toJson(obj);
            } catch (Exception e) {
    
                logger.error("Exception for toJson(obj, dateFormat) : " + e.getMessage());
                return gson.toJson(obj);
            }
        }
    
        public static String toJson(Object target, Type targetType) {
    
            String result = EMPTY_JSON;
    
            if (target == null)
                return result;
    
            try {
                if (targetType != null) {
                    result = gson.toJson(target, targetType);
                } else {
                    result = gson.toJson(target);
                }
            } catch (Exception ex) {
                logger.error("JsonUtil.toJson(target, targetType) exception, return empty json, exception for "
                        + target.toString() + " : " + ex.getMessage());
                if (target instanceof Collection || target instanceof Iterator || target instanceof Enumeration
                        || target.getClass().isArray()) {
                    result = EMPTY_JSON_ARRAY;
                } else
                    result = EMPTY_JSON;
            }
            return result;
        }
    
        /**
         * to covert a string to a class
         * @param json
         * @param classOfT
         */
        public static <T> T fromJson(String json, Class<T> classOfT) {
            return gson.fromJson(json, classOfT);
        }
    
        /**
         * to covert a string to a class
         * @param json
         * @param classOfT
         */
        public static <T> T fromJson(String json, Class<T> classOfT, String dateFormat) {
            return builder.setDateFormat(dateFormat).serializeSpecialFloatingPointValues().create().fromJson(json, classOfT);
        }
    
        public static <T> T fromJson(String json, Type type) {
            return gson.fromJson(json, type);
        }
    
        /**
         * to covert a JsonElement to a class
         * @param json
         * @param classOfT
         */
        public static <T> T fromJson(JsonElement jsonElem, Class<T> classOfT) {
            return gson.fromJson(jsonElem, classOfT);
        }
    
        /**
         * convert json string to list
         * @param jsonStr
         * @param type
         */
        public static List<?> jsonToList(String json, Type type) {
            List<?> objList = gson.fromJson(json, type);
            return objList;
        }
    
        /**
         * convert json to map
         * @param jsonStr
         */
        public static Map<?, ?> jsonToMap(String json) {
            Type type = new TypeToken<Map<?, ?>>() {
            }.getType();
            Map<?, ?> objMap = gson.fromJson(json, type);
            return objMap;
        }
    
        public static void main(String[] args) {
            Map<String, Object> obj = new HashMap<String, Object>();
            obj.put("k1", "k1v");
            obj.put("k2", 2);
            try {
                obj.put("k3", parseDate("2013-01-02"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            System.out.println(JsonUtil.toJson(obj));
            System.out.println(JsonUtil.toJson(obj, "yyyy-MM-dd"));
            System.out.println(JsonUtil.toJson(obj));
    
        }
    
        public class JsonDateDeserializer implements JsonDeserializer<Date> {
            public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                    throws JsonParseException {
                String s = json.getAsJsonPrimitive().getAsString();
                try {
                    return parseDate(s);
                } catch (ParseException e) {
                    throw new JsonParseException(e);
                }
            }
        }
    
        public static Date parseDate(String s) throws ParseException {
            if (s.indexOf("-") == 4) {
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
                return df.parse(s);
            }
            String value = s;
            if (!value.endsWith("d")) {
                if (value.charAt(2) == '/')
                    return new SimpleDateFormat("MM/dd/yy").parse(value);
                else
                    return new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(value);
            } else {
                value = value.substring(0, value.length() - 1);
                if (value != null) {
                    if (value.startsWith(""") && value.endsWith("""))
                        return new SimpleDateFormat(""ddMMMyy"").parse(value);
                    else if (value.startsWith("'") && value.endsWith("'"))
                        return new SimpleDateFormat("''ddMMMyy''").parse(value);
                    else
                        throw new ParseException("incorrect format for Date(" + s + "): correct format is 'ddMMMyy'd", 0);
                }
            }
            return null;
        }
    
    }
    
    -----------------------------------------------------------------------------------------------------------------------
    package com.csf.practicetest.json.entity;
    
    import java.io.Serializable;
    
    public class RespObj implements Serializable {
    
        private String code;
        private String type;
        private Object message;
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public String getType() {
            return type;
        }
    
        public Object getMessage() {
            return message;
        }
    
        public void setMessage(Object message) {
            this.message = message;
        }
    
        public void setType(String type) {
            this.type = type;
        }
    
    }
    -----------------------------------------------------------------------------------
    package com.csf.practicetest.json.entity;
    
    
    /**
     * @author fenglei.ma 2017年1月6日 16:52
     */
    public class XcfRpoertAnalyseSimplify {
    
        private String name;// 图片名称
        private String url;// 图片url
        private String id;// 图片编号
        private String dt;
        private String p;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getUrl() {
            return url;
        }
    
        public void setUrl(String url) {
            this.url = url;
        }
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getDt() {
            return dt;
        }
    
        public void setDt(String dt) {
            this.dt = dt;
        }
    
        public String getP() {
            return p;
        }
    
        public void setP(String p) {
            this.p = p;
        }
    
        @Override
        public String toString() {
            return "XcfRpoertAnalyseSimplify [name=" + name + ", url=" + url + ", id=" + id + ", dt=" + dt + ", p=" + p
                    + "]";
        }
    
    }
  • 相关阅读:
    开放平台架构指南
    绝了!起个好标题的9大技巧
    ASP已老,尚能饭否?
    离职,问题就解决了吗?
    什么是草台班子?
    回忆我的第一个软件项目
    Vue3中的Composables组合式函数,Vue3实现minxins
    Vue3中的teleport节点传送
    js中if逻辑过多,常见review优化
    QT安装
  • 原文地址:https://www.cnblogs.com/xiaolei2017/p/8743705.html
Copyright © 2020-2023  润新知