使用jackson将对象中数值转换为String

问题描述:

在项目中使用Long作为表主键,在前后端交互时,由于long类型传递到前端会引起精度问题,所以要求返回给前端的json中long类型数值必须为String,于是提供本方法。参考了使用fastjson转换的案例,链接:fastjson将对象中数值转换为String

代码如下,拷贝即可

public class JSONUtils {

    private static final ObjectMapper mapper = new ObjectMapper();

    public static Object setNumberValueToString(String json) throws IOException {
        if (json instanceof String) {
            JsonNode rootNode = mapper.readTree(json);
            if (rootNode.isObject()) {
                return toObjectNode((ObjectNode) rootNode);
            } else if (rootNode.isArray()) {
                return toArrayNode((ArrayNode) rootNode);
            }
        } else {
            throw new RuntimeException("json is not String type");
        }
        return json;
    }

    private static ObjectNode toObjectNode(ObjectNode node) throws IOException {
        ObjectNode newNode = mapper.createObjectNode();
        Iterator<Map.Entry<String, JsonNode>> iterator = node.fields();
        while (iterator.hasNext()) {
            Map.Entry<String, JsonNode> entry = iterator.next();
            // 处理 entry
            JsonNode valueNode = entry.getValue();
            if (valueNode.isNumber()) {
                newNode.put(entry.getKey(), valueNode.asText());
            } else if (valueNode.isObject()) {
                newNode.set(entry.getKey(), toObjectNode((ObjectNode) valueNode));
            } else if (valueNode.isArray()) {
                newNode.set(entry.getKey(), toArrayNode((ArrayNode) valueNode));
            } else {
                newNode.set(entry.getKey(), valueNode);
            }
        }
        return newNode;
    }

    private static ArrayNode toArrayNode(ArrayNode node) throws IOException {
        ArrayNode newNode = mapper.createArrayNode();
        for (JsonNode element : node) {
            if (element.isObject()) {
                newNode.add(toObjectNode((ObjectNode) element));
            } else if (element.isArray()) {
                newNode.add(toArrayNode((ArrayNode) element));
            } else {
                newNode.add(element);
            }
        }
        return newNode;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值