栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Java 对象toString()之后转化成json对象

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java 对象toString()之后转化成json对象

在平时的工作中经常遇到Java对象toString()之后打印出来,在发生线上问题时需要参数重新调用时,无法转化参数

如下图:

[TransOccupyRequestDTO(newOrderId=390310807, transOccupyDetails=[TransOccupyDetail(orderId=389507562, orderType=3Sent, orderListId=811181368, newOrderId=390310807, newOrderListId=812635303, batchId=197987597, num=2), TransOccupyDetail(orderId=389507562, orderType=3Sent, orderListId=811181368, newOrderId=390310807, newOrderListId=812635303, batchId=197987597, num=1), TransOccupyDetail(orderId=389507562, orderType=3Sent, orderListId=811181369, newOrderId=390310807, newOrderListId=811181369, batchId=202747933, num=4)])]

下面是一个工具类实现Java对象转化成json 

import com.alibaba.fastjson.JSON;
import javafx.util.Pair;
import org.apache.commons.lang.StringUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

public class ToStringUtils {

    

    
    public static Pattern datePattern = Pattern.compile("^[a-zA-Z]{3} [a-zA-Z]{3} [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} CST ((19|20)\d{2})$");
    public static Pattern numPattern = Pattern.compile("^-?[0-9]+\.?[0-9]*$");
    public static Pattern objectPattern = Pattern.compile("^[a-zA-Z0-9\.]+\(.+\)$");
    public static Pattern listPattern = Pattern.compile("^\[.*\]$");
    public static Pattern mapPattern = Pattern.compile("^\{.*\}$");
    public static Pattern supperPattern = Pattern.compile("^super=[a-zA-Z0-9\.]+\(.+\)$");
    public static final String NULL = "null";

    
    public static String toJSONString(String toString) throws ParseException {
        return JSON.toJSONString(toMap(toString));
    }

    
    public static  T toObject(String toString, Class clazz) throws ParseException {
        return JSON.parseObject(toJSONString(toString), clazz);
    }

    
    private static Map toMap(String toString) throws ParseException {
        if (StringUtils.isEmpty(toString = StringUtils.trim(toString))) {
            return toString == null ? null : new HashMap<>();
        }

        // 移除最外层"()"
        toString = StringUtils.substringAfter(toString, "(").trim();
        toString = StringUtils.substringBeforeLast(toString, ")").trim();

        String token;
        Map map = new HashMap<>();
        while (StringUtils.isNotEmpty(toString) && StringUtils.isNotEmpty(token =splitToken(toString))) {
            toString = StringUtils.removeStart(StringUtils.removeStart(toString, token).trim(), ",").trim();

            // 如果带"super="(lombok的@ToString(callSuper=true)引入),按照当前层继续处理
            if (supperPattern.matcher(token).matches()) {
                token = token.substring(token.indexOf("(") + 1, token.length() - 1);
                toString = String.format("%s,%s", token, toString);
                continue;
            }

            Pair keyValue = parseToken(token);
            map.put(keyValue.getKey(), buildTypeValue(keyValue.getKey(), keyValue.getValue()));
        }
        return map;
    }
    static Pair parseToken(String token) {
        assert Objects.nonNull(token) && token.contains("=");
        int pos = token.indexOf("=");
        return new javafx.util.Pair<>(token.substring(0, pos), token.substring(pos + 1));
    }

    
    private static Object buildTypeValue(String key, String value) throws ParseException {
        if (StringUtils.isEmpty(value)) {
            return null;
        } else if (value.equals(NULL)) {
            return null;
        }

        // 日期类型
        if (datePattern.matcher(value).matches()) {
            return new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", new Locale("us")).parse(value).getTime();
        }
        // 数字类型
        if (numPattern.matcher(value).matches()) {
            return value;
        }
        // 集合类型
        if (listPattern.matcher(value).matches()) {
            return buildListValue(value);
        }
        // map类型
        if (mapPattern.matcher(value).matches()) {
            return buildMapValue(value);
        }
        // 对象类型
        if (objectPattern.matcher(value).matches()) {
            return toMap(value);
        }

        // 其他都认为是string类型
        return value;
    }

    
    private static Object buildListValue(String value) throws ParseException {
        List result = new ArrayList<>();

        value = value.substring(1, value.length() - 1).trim();
        if (StringUtils.isEmpty(value)) {
            return result;
        }

        String token = null;
        while (StringUtils.isNotBlank(value) && StringUtils.isNotBlank(token = splitToken(value))) {
            result.add(buildTypeValue(null, token));
            value = StringUtils.removeStart(StringUtils.removeStart(value, token).trim(), ",").trim();
        }

        return result;
    }

    static String splitToken(String toString) {
        if (StringUtils.isBlank(toString)) {
            return toString;
        }

        int bracketNum = 0;
        Stack stack = new Stack<>();
        for (int i = 0; i < toString.length(); i++) {
            Character c = toString.charAt(i);
            if (tokenMap.containsValue(c)) {
                stack.push(c);
            } else if (tokenMap.containsKey(c) && Objects.equals(stack.peek(), tokenMap.get(c))) {
                stack.pop();
            } else if ((c == ',') && stack.isEmpty()) {
                return toString.substring(0, i);
            }
        }
        if (stack.isEmpty()) {
            return toString;
        }
        throw new RuntimeException("splitFirstToken error, bracketNum=" + bracketNum + ", toString=" + toString);
    }

    
    private final static Map tokenMap = new HashMap<>();
    static {
        tokenMap.put(')', '(');
        tokenMap.put('}', '{');
        tokenMap.put(']', '[');
    }


    
    private static Map buildMapValue(String value) throws ParseException {
        Map result = new HashMap<>();
        value = value.substring(1, value.length() - 1).trim();
        if (StringUtils.isEmpty(value)) {
            return result;
        }

        String token = null;
        while (StringUtils.isNotEmpty(token =splitToken(value))) {
            Pair keyValue =parseToken(token);
            result.put(buildTypeValue(keyValue.getKey(), keyValue.getKey()), buildTypeValue(keyValue.getKey(), keyValue.getValue()));

            value = StringUtils.removeStart(StringUtils.removeStart(value, token).trim(), ",").trim();
        }

        return result;
    }



}
 

最终测试结果

String str="[TransOccupyRequestDTO(newOrderId=390310807, transOccupyDetails=[TransOccupyDetail(orderId=389507562, orderType=3Sent, orderListId=811181368, newOrderId=390310807, newOrderListId=812635303, batchId=197987597, num=2), TransOccupyDetail(orderId=389507562, orderType=3Sent, orderListId=811181368, newOrderId=390310807, newOrderListId=812635303, batchId=197987597, num=1), TransOccupyDetail(orderId=389507562, orderType=3Sent, orderListId=811181369, newOrderId=390310807, newOrderListId=811181369, batchId=202747933, num=4)])]";
TransOccupyRequestDTO transOccupyRequestDTO = ToStringUtils.toObject(str,TransOccupyRequestDTO.class);
System.out.println(JSON.toJSON(transOccupyRequestDTO));

Connected to the target VM, address: '127.0.0.1:62799', transport: 'socket'
{"newOrderId":390310807,"transOccupyDetails":[{"orderType":"3Sent","orderListId":811181368,"orderId":389507562,"newOrderId":390310807,"newOrderListId":812635303,"num":2,"batchId":197987597},{"orderType":"3Sent","orderListId":811181368,"orderId":389507562,"newOrderId":390310807,"newOrderListId":812635303,"num":1,"batchId":197987597},{"orderType":"3Sent","orderListId":811181369,"orderId":389507562,"newOrderId":390310807,"newOrderListId":811181369,"num":4,"batchId":202747933}]}
Disconnected from the target VM, address: '127.0.0.1:62799', transport: 'socket'

转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号