JAVA对象转JSON字符串时格式化日期_oracle clob转字符串

JAVA对象转JSON字符串时格式化日期_oracle clob转字符串本案例所有代码均为原创,使用Java手写,没有借鉴其他类似工具库和网上论坛博客,也许没有经过充分测试,可能出现未知bug,因此不建议拿到正式的项目里使用。Java对象就像一个文件夹一样,没有办法知道其深度,所以采用了递归。性能方面没有测试,个人认为没有特别耗费性能的地方,除非你的对象包含很多层级。它可以支持null,字符串,数字、日期、集合等多种类型,包括以上类型的多层嵌套,都没有问题。源码不多,如下:importjava.lang.reflect.Field;importjava.lang

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

本案例所有代码均为原创,使用Java1.8类库编写,没有借鉴其他类似工具库和网上论坛博客,也许没有经过充分测试,可能出现未知bug,仅供参考学习使用。

Java对象就像一个文件夹一样,没有办法知道其深度,所以采用了递归。

性能方面没有测试,个人认为没有特别耗费性能的地方,除非你的对象包含很多层级。

它可以支持null,字符串,数字、日期、集合、数组以及自定义对象 等多种数据类型,包括以上任意类型的多层嵌套。

另外对于存储基本类型元素的数组而言,实在没有更好的处理办法,因此占用了很多代码行数。

源码不多,如下:

package com.duyi.boot.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/** * @author qiaoao * @description: * @date 2021/7/29 18:10 */
public class JsonUtil { 
   

    private static JsonUtil util = new JsonUtil();

    public static String toJsonStr(Object obj) { 
   
        return util.parseObj(obj, new StringBuilder());
    }

    private String parseObj(Object obj, StringBuilder builder) { 
   
        if (builder == null) { 
   
            throw new UnsupportedOperationException("builder can not be null");
        }
        if (obj == null) { 
   
            return builder.append("\"null\"").toString();
        }
        Class clazz = obj.getClass();
        if (Collection.class.isAssignableFrom(clazz)) { 
   
            Iterator iterator = ((Collection) obj).iterator();
            builder.append("[");
            while (iterator.hasNext()) { 
   
                parseObj(iterator.next(), builder);
                if (iterator.hasNext())
                    builder.append(",");
            }
            builder.append("]");
        } else if (Map.class.isAssignableFrom(clazz)) { 
   
            //如果是map,key一定且必须是String类型,如果是对象,给他toString()
            Map map = ((Map) obj);
            Iterator iterator = map.keySet().iterator();
            builder.append("{");
            while (iterator.hasNext()) { 
   
                Object key = iterator.next();
                builder.append("\"");
                builder.append(key);
                builder.append("\":");
                parseObj(map.get(key), builder);
                if (iterator.hasNext())
                    builder.append(",");
            }
            builder.append("}");
        } else if (clazz.isArray()) { 
   
            //数组
            /** * 虽然int[]类型的数组可以通过:Arrays.stream((int[]) obj).boxed().collect(Collectors.toList()); * 转化为集合,但Arrays.stream()方法不支持char[] byte[] boolean[] float[] */
            builder.append("[");
            if (obj instanceof int[]) { 
   
                arrayHandle((int[]) obj, builder);
            } else if (obj instanceof byte[]) { 
   
                arrayHandle((byte[]) obj, builder);
            } else if (obj instanceof char[]) { 
   
                arrayHandle((char[]) obj, builder);
            } else if (obj instanceof long[]) { 
   
                arrayHandle((long[]) obj, builder);
            } else if (obj instanceof float[]) { 
   
                arrayHandle((float[]) obj, builder);
            } else if (obj instanceof short[]) { 
   
                arrayHandle((short[]) obj, builder);
            } else if (obj instanceof double[]) { 
   
                arrayHandle((double[]) obj, builder);
            } else if (obj instanceof boolean[]) { 
   
                arrayHandle((boolean[]) obj, builder);
            } else if (obj instanceof Object[]) { 
   
                List<Object> list = Arrays.asList((Object[]) obj);
                for (int i = 0; i < list.size(); i++) { 
   
                    parseObj(list.get(i), builder);
                    if (i < list.size() - 1) { 
   
                        builder.append(",");
                    }
                }
            } else { 
   
                throw new UnsupportedOperationException(obj.getClass().toString());
            }
            builder.append("]");
        } else if (String.class.isAssignableFrom(clazz) || Date.class.isAssignableFrom(clazz)) { 
   
            builder.append("\"");
            builder.append(obj);
            builder.append("\"");
        } else if (Number.class.isAssignableFrom(clazz) || Boolean.class.isAssignableFrom(clazz)) { 
   
            builder.append(obj);
        } else { 
   
            //自定义的实体类
            Field[] fields = clazz.getDeclaredFields();
            builder.append("{");
            for (int i = 0; i < fields.length; i++) { 
   
                Field field = fields[i];
                if (Modifier.isPrivate(field.getModifiers())) { 
   
                    field.setAccessible(true);
                }
                builder.append("\"");
                builder.append(field.getName());
                builder.append("\":");
                Object value = null;
                try { 
   
                    value = field.get(obj);
                } catch (IllegalAccessException e) { 
   
                    e.printStackTrace();
                }
                parseObj(value, builder);
                if (i < fields.length - 1) { 
   
                    builder.append(",");
                }
            }
            builder.append("}");
        }
        return builder.toString();
    }

    private void arrayHandle(int[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }

    private void arrayHandle(byte[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }

    private void arrayHandle(char[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }

    private void arrayHandle(long[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }

    private void arrayHandle(float[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }

    private void arrayHandle(short[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }

    private void arrayHandle(double[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }

    private void arrayHandle(boolean[] arr, StringBuilder builder) { 
   
        for (int i = 0; i < arr.length; i++) { 
   
            parseObj(arr[i], builder);
            if (i < arr.length - 1) { 
   
                builder.append(",");
            }
        }
    }
}


以下为测试代码:

import java.util.*;

/** * @author qiaoao * @description: * @date 2021/7/30 14:06 */
public class Demo { 
   
    private long aLong;
    private int aInt;
    public short aShort;
    private static boolean isAlive;
    private String name;
    private byte[] bytes;
    private Date[] dates;
    private int[][][] superIntArr;
    private String[][] strings;
    private List<Map<Integer,String>> list;
    private Set<int[]> set;
    private Map<String,List<int[]>> map;

    public static void main(String[] args) throws IllegalAccessException { 
   
        Demo demo = Demo.getObj();
        String json = JsonUtil.toJsonStr(demo);
        System.out.println(json);
    }

    public static Demo getObj(){ 
   
        Demo demo = new Demo();
        demo.setaLong(1000012L);
        demo.setaInt(120);
        Demo.setIsAlive(true);
        demo.setaShort((short)78);
        demo.setName("Demo Test");
        byte[] bytes = new byte[2];
        bytes[0] = 1;
        bytes[1] = 127;
        demo.setBytes(bytes);
        Date[] dates = new Date[3];
        dates[1] = new Date();
        demo.setDates(dates);
        int[][][] superIntArr = new int[2][2][2];
        for (int i = 0;i<superIntArr.length;i++){ 
   
            for (int j = 0;j<superIntArr[i].length;j++){ 
   
                for (int k = 0;k<superIntArr[j].length;k++){ 
   
                    superIntArr[i][j][k] = (int)(Math.random()*100);
                }
            }
        }
        demo.setSuperIntArr(superIntArr);
        String[][] strings = new String[5][2];
        for (int i = 0; i < strings.length; i++) { 
   
            for (int j = 0; j < strings[i].length; j++) { 
   
                strings[i][j] = String.valueOf(Math.random());
            }
        }
        demo.setStrings(strings);
        List<Map<Integer,String>> list = new LinkedList<>();
        Map<Integer,String> map = new Hashtable<>();
        map.put(1,"demo1");
        map.put(2,"demo2");
        map.put(3,"demo3");
        Map<Integer,String> map2 = new Hashtable<>();
        map2.put(12,"demo12");
        map2.put(22,"demo22");
        map2.put(32,"demo32");
        list.add(map);
        list.add(map2);
        demo.setList(list);
        Set<int[]> set = new HashSet<>();
        for (int i = 0;i<5;i++){ 
   
            int len = (int)(Math.random()*10)+2;
            int[] tempArr = new int[len];
            for (int j = 0; j < tempArr.length; j++) { 
   
                tempArr[j] = 100 - j;
            }
            set.add(tempArr);
        }
        demo.setSet(set);
        Map<String,List<int[]>> maps = new LinkedHashMap<>();
        for (int i = 0;i<=3;i++){ 
   
            List<int[]> tempList = new Stack<>();
            for (int j = 20;j>=0;j--){ 
   
                int[] hh = new int[5];
                for (int k = 0; k < hh.length; k++) { 
   
                    hh[k] = k+j;
                }
                tempList.add(hh);
            }
            maps.put("list"+i,tempList);
        }
        demo.setMap(maps);
        return demo;
    }

    public static void setIsAlive(boolean isAlive) { 
   
        Demo.isAlive = isAlive;
    }

    public void setaLong(long aLong) { 
   
        this.aLong = aLong;
    }

    public void setaInt(int aInt) { 
   
        this.aInt = aInt;
    }

    public void setaShort(short aShort) { 
   
        this.aShort = aShort;
    }

    public void setName(String name) { 
   
        this.name = name;
    }

    public void setBytes(byte[] bytes) { 
   
        this.bytes = bytes;
    }

    public void setDates(Date[] dates) { 
   
        this.dates = dates;
    }

    public void setSuperIntArr(int[][][] superIntArr) { 
   
        this.superIntArr = superIntArr;
    }

    public void setStrings(String[][] strings) { 
   
        this.strings = strings;
    }

    public void setList(List<Map<Integer, String>> list) { 
   
        this.list = list;
    }

    public void setSet(Set<int[]> set) { 
   
        this.set = set;
    }

    public void setMap(Map<String, List<int[]>> map) { 
   
        this.map = map;
    }
}

执行结果如下:

{ 
   "aLong":1000012,"aInt":120,"aShort":78,"isAlive":true,"name":"Demo Test","bytes":[1,127],"dates":["null","Fri Jul 30 15:25:35 CST 2021","null"],"superIntArr":[[[11,99],[47,20]],[[20,72],[59,49]]],"strings":[["0.11307908409828815","0.22341871804534985"],["0.5005992982006673","0.5893604912974005"],["0.6892806476807729","0.4169059518233631"],["0.650889741691504","0.8702143841026739"],["0.26192826894369403","0.31877430959379016"]],"list":[{ 
   "3":"demo3","2":"demo2","1":"demo1"},{ 
   "32":"demo32","12":"demo12","22":"demo22"}],"set":[[100,99,98],[100,99,98,97,96,95],[100,99,98,97,96,95,94,93,92,91],[100,99,98,97,96,95,94,93],[100,99,98,97,96,95,94,93]],"map":{ 
   "list0":[[20,21,22,23,24],[19,20,21,22,23],[18,19,20,21,22],[17,18,19,20,21],[16,17,18,19,20],[15,16,17,18,19],[14,15,16,17,18],[13,14,15,16,17],[12,13,14,15,16],[11,12,13,14,15],[10,11,12,13,14],[9,10,11,12,13],[8,9,10,11,12],[7,8,9,10,11],[6,7,8,9,10],[5,6,7,8,9],[4,5,6,7,8],[3,4,5,6,7],[2,3,4,5,6],[1,2,3,4,5],[0,1,2,3,4]],"list1":[[20,21,22,23,24],[19,20,21,22,23],[18,19,20,21,22],[17,18,19,20,21],[16,17,18,19,20],[15,16,17,18,19],[14,15,16,17,18],[13,14,15,16,17],[12,13,14,15,16],[11,12,13,14,15],[10,11,12,13,14],[9,10,11,12,13],[8,9,10,11,12],[7,8,9,10,11],[6,7,8,9,10],[5,6,7,8,9],[4,5,6,7,8],[3,4,5,6,7],[2,3,4,5,6],[1,2,3,4,5],[0,1,2,3,4]],"list2":[[20,21,22,23,24],[19,20,21,22,23],[18,19,20,21,22],[17,18,19,20,21],[16,17,18,19,20],[15,16,17,18,19],[14,15,16,17,18],[13,14,15,16,17],[12,13,14,15,16],[11,12,13,14,15],[10,11,12,13,14],[9,10,11,12,13],[8,9,10,11,12],[7,8,9,10,11],[6,7,8,9,10],[5,6,7,8,9],[4,5,6,7,8],[3,4,5,6,7],[2,3,4,5,6],[1,2,3,4,5],[0,1,2,3,4]],"list3":[[20,21,22,23,24],[19,20,21,22,23],[18,19,20,21,22],[17,18,19,20,21],[16,17,18,19,20],[15,16,17,18,19],[14,15,16,17,18],[13,14,15,16,17],[12,13,14,15,16],[11,12,13,14,15],[10,11,12,13,14],[9,10,11,12,13],[8,9,10,11,12],[7,8,9,10,11],[6,7,8,9,10],[5,6,7,8,9],[4,5,6,7,8],[3,4,5,6,7],[2,3,4,5,6],[1,2,3,4,5],[0,1,2,3,4]]}}

可以放到 json 在线格式化页面里检验:
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/190895.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • Android Okio应用及解析

    Android Okio应用及解析自从Google官方将OkHttp作为底层的网络请求之后,作为OkHttp底层IO操作的Okio也是走进开发者的视野,这个甚至是取代了java的原生IO库的存在到底有什么特殊的本领呢?这篇文章主要是对Okio的实现做一个详尽的解析,当然由于笔者分析中可能有纰漏的地方,也烦请指出,Okio的代码比较精巧,核心的代码大约5000行,对文章不尽兴的也可以直接通读源码,这样就能理解的更清晰。全文较长,这里…

  • 怎么检查计算机和打印机是否连接网络,检查电脑是否正确连接网络打印机

    怎么检查计算机和打印机是否连接网络,检查电脑是否正确连接网络打印机我们有时候会在电脑中连接网络打印机来进行打印工作。可是有用户会遇到文件无法打印的问题。那么这个时候应该怎么检查电脑中是否已成功连接网络打印机?对此,我们可以参考以下方法来进行操作。1、如果文件打印不了,按Crtl+P打开打印对话框,在打印机名称中看看有没有网络打印机的名称,如果没有则说明打印机驱动有问题,需要重新安装网络打印机的驱动程序;2、如果有显示打印机名称,那么问题有可能是网络连接错误或者打…

  • 正交矩阵的模_正交矩阵的向量组

    正交矩阵的模_正交矩阵的向量组本节主要讲解正交(orthogonal)概念对于向量、基和子空间的意义。1.正交向量Orthogonalvectors2.正交子空间Orthogonalsubspaces3.零空间与行空间正交Nullspaceisperpendiculartorowspace4.矩阵A^TA

    2022年10月22日
  • docker(1)下载安装for mac

    docker(1)下载安装for mac前言Docker提供轻量的虚拟化,你能够从Docker获得一个额外抽象层,你能够在单台机器上运行多个Docker微容器,而每个微容器里都有一个微服务或独立应用,例如你可以将Tomcat运行在一个D

  • Python绘制五角星

    Python绘制五角星importturtle#引用turtle库大部分<a>.<b>()#.代表使用a中的函数调用函数<a>中的函数<b>()turtle.fo

  • 对象转map工具类BeanUtil

    对象转map工具类BeanUtil1、2、当isAccessible()的结果是false时不允许通过反射访问private变量。packagecom.yung.ppapi.util;importjava.beans.BeanInfo;importjava.beans.Introspector;importjava.beans.PropertyDescriptor;importjava.lang.re…

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号