大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新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账号...