ObjectNode 工具类


package com.kyexpress.dsp.common.utils;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.ParseException;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.BooleanNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.NumericNode;
import com.fasterxml.jackson.databind.node.ObjectNode;


public final class JsonNodeUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(JsonNodeUtils.class);

    private static ObjectMapper objectMapper = new ObjectMapper();

    public static final String DATE_TIME_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String DATE_FORMAT_PATTERN = "yyyy-MM-dd";

    public static final FastDateFormat DATE_TIME_FORMAT = FastDateFormat.getInstance(DATE_TIME_FORMAT_PATTERN);
    public static final FastDateFormat DATE_FORMAT = FastDateFormat.getInstance(DATE_FORMAT_PATTERN);

    static{
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }

    public static void setObjectMapper(final ObjectMapper objectMapper) {
        JsonNodeUtils.objectMapper = objectMapper;
    }

    public static String writeValueAsString(final Object value) {
        if (value == null) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(value);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage(), e);
        }
        return null;
    }

    public static <T> T readValue(final JsonNode jsonNode, final Class<T> valueType) {
        if (jsonNode == null) {
            return null;
        }
        try {
            return objectMapper.readValue(jsonNode.traverse(), valueType);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage(), e);
        }
        return null;
    }

    public static JsonNode readTree(final String content) {
        if (StringUtils.isEmpty(content)) {
            return NullNode.getInstance();
        }
        try {
            return objectMapper.readTree(content);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage(), e);
        }
        return NullNode.getInstance();
    }

    public static JsonNode readTree(final File file) {
        if (file == null || !file.isFile()) {
            return NullNode.getInstance();
        }
        try {
            return objectMapper.readTree(file);
        } catch (IOException e) {
            LOGGER.warn(e.getMessage(), e);
        }
        return NullNode.getInstance();
    }

    public static boolean isArray(final JsonNode jsonNode) {
        if (jsonNode == null) {
            return false;
        }
        return jsonNode.isArray();
    }

    public static boolean isNotArray(final JsonNode jsonNode) {
        return !isArray(jsonNode);
    }

    public static boolean isObject(final JsonNode jsonNode) {
        if (jsonNode == null) {
            return false;
        }
        return jsonNode.isObject();
    }

    public static boolean isNotObject(final JsonNode jsonNode) {
        return !isObject(jsonNode);
    }

    public static boolean isNull(final JsonNode jsonNode) {
        if (jsonNode == null) {
            return true;
        }
        return jsonNode.isNull();
    }

    public static boolean isNotNull(final JsonNode jsonNode) {
        return !isNull(jsonNode);
    }

    public static long asLong(final JsonNode data, final String key) {
        return asLong(data, key, 0L);
    }

    public static long asLong(final JsonNode data, final String key, final long defaultValue) {
        if (data == null) {
            return defaultValue;
        }
        final JsonNode jsonNode = data.get(key);
        if (isNull(jsonNode)) {
            return defaultValue;
        }
        return jsonNode.asLong(defaultValue);
    }

    public static Long asLong(final JsonNode data, final String key, final Long defaultValue) {
        if (data == null) {
            return defaultValue;
        }
        final JsonNode jsonNode = data.get(key);
        if (isNull(jsonNode)) {
            return defaultValue;
        }
        if (jsonNode instanceof NumericNode) {
            return Long.valueOf(jsonNode.asLong());
        }
        if (jsonNode instanceof BooleanNode) {
            return Long.valueOf(jsonNode.asLong());
        }
        try {
            return Long.valueOf(new BigDecimal(jsonNode.asText()).longValue());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public static String asText(final JsonNode data) {
        if (isNull(data)) {
            return "";
        }
        return data.asText("");
    }

    public static String asText(final JsonNode data, final String key) {
        return asText(data, key, "");
    }

    public static String asText(final JsonNode data, final String key, final String defaultValue) {
        if (data == null) {
            return defaultValue;
        }
        final JsonNode jsonNode = data.get(key);
        if (isNull(jsonNode)) {
            return defaultValue;
        }
        return jsonNode.asText(defaultValue);
    }

    public static int asInt(final JsonNode data, final String key) {
        return asInt(data, key, 0);
    }

    public static int asInt(final JsonNode data, final String key, final int defaultValue) {
        if (data == null) {
            return defaultValue;
        }
        final JsonNode jsonNode = data.get(key);
        if (isNull(jsonNode)) {
            return defaultValue;
        }
        return jsonNode.asInt(defaultValue);
    }

    public static Integer asInt(final JsonNode data, final String key, final Integer defaultValue) {
        if (data == null) {
            return defaultValue;
        }
        final JsonNode jsonNode = data.get(key);
        if (isNull(jsonNode)) {
            return defaultValue;
        }
        if (jsonNode instanceof NumericNode) {
            return Integer.valueOf(jsonNode.asInt());
        }
        if (jsonNode instanceof BooleanNode) {
            return Integer.valueOf(jsonNode.asInt());
        }
        try {
            return Integer.valueOf(new BigDecimal(jsonNode.asText()).intValue());
        } catch (NumberFormatException e) {
            return defaultValue;
        }
    }

    public static Number asNumber(JsonNode data, String key, Number defaultValue) {
        if (isNull(data)) {
            return defaultValue;
        }
        final JsonNode jsonNode = data.get(key);
        if (isNull(jsonNode)) {
            return defaultValue;
        }
        final Number value = jsonNode.numberValue();
        if (value != null) {
            return value;
        }
        try {
            return new BigDecimal(jsonNode.asText());
        } catch (Exception e) {
            return defaultValue;
        }
    }

    public static Timestamp asTimestamp(final JsonNode data, final String key, final Timestamp defaultValue) {
        if (isNull(data)) {
            return defaultValue;
        }
        final JsonNode jsonNode = data.get(key);
        if (isNull(jsonNode)) {
            return defaultValue;
        }
        final Number numberValue = jsonNode.numberValue();
        if (numberValue != null) {
            return new Timestamp(numberValue.longValue());
        }
        final String textValue = StringUtils.trimToEmpty(jsonNode.asText());
        if (NumberUtils.isDigits(textValue)) {
            return new Timestamp(NumberUtils.toLong(textValue, 0));
        }

        if (textValue.length() == DATE_TIME_FORMAT_PATTERN.length()) {
            try {
                return new Timestamp(DATE_TIME_FORMAT.parse(textValue).getTime());
            } catch (ParseException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
        if (textValue.length() == DATE_FORMAT_PATTERN.length()) {
            try {
                return new Timestamp(DATE_FORMAT.parse(textValue).getTime());
            } catch (ParseException e) {
                LOGGER.error(e.getMessage(), e);
            }
        }
        return defaultValue;
    }

    public static JsonNode get(final JsonNode data, final String key) {
        if (data == null) {
            return NullNode.getInstance();
        }
        final JsonNode jsonNode = data.get(key);
        if (jsonNode == null) {
            return NullNode.getInstance();
        }
        return jsonNode;
    }

    public static JsonNode get(final JsonNode data, final int index) {
        if (data == null) {
            return NullNode.getInstance();
        }
        final JsonNode jsonNode = data.get(index);
        if (jsonNode == null) {
            return NullNode.getInstance();
        }
        return jsonNode;
    }

    public static ObjectNode putObject(final ObjectNode objectNode, final String fieldName) {
        final JsonNode jsonNode = objectNode.get(fieldName);
        if (jsonNode instanceof ObjectNode) {
            return (ObjectNode) jsonNode;
        }
        return objectNode.putObject(fieldName);
    }

    public static ObjectNode putObject(final ArrayNode arrayNode, final int index) {
        final JsonNode jsonNode = arrayNode.get(index);
        if (jsonNode instanceof ObjectNode) {
            return (ObjectNode) jsonNode;
        }
        while (arrayNode.size() <= index) {
            arrayNode.addNull();
        }
        final ObjectNode objectNode = arrayNode.objectNode();
        arrayNode.set(index, objectNode);
        return objectNode;
    }

    public static ArrayNode putArray(final ObjectNode objectNode, final String fieldName) {
        final JsonNode jsonNode = objectNode.get(fieldName);
        if (jsonNode instanceof ArrayNode) {
            return (ArrayNode) jsonNode;
        }
        return objectNode.putArray(fieldName);
    }

    private JsonNodeUtils() {
    }
}
 

JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。在Java中,可以使用许多第三方库来处理JSON数据。常见的有Jackson、Gson、Fastjson等。接下来我以Jackson为例,演示如何使用Java代码实现JSON的添加、删除和更新操作。 首先,需要引入Jackson的相关依赖。在Maven项目中,可以在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.12.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.5</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.12.5</version> </dependency> ``` 接下来,我们可以定义一个简单的JSON字符串作为示例数据: ``` String jsonString = "{\"name\":\"张三\",\"age\":20,\"gender\":\"男\",\"hobby\":[\"篮球\",\"游泳\"]}"; ``` 将jsonString转化为Java对象,可以使用以下代码: ``` ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonString); ``` 其中,ObjectMapper是Jackson中最常用的类之一,用于将Java对象序列化为JSON字符串或将JSON字符串反序列化为Java对象。JsonNode则表示JSON中的一个节点,可以表示一个对象、一个数组或一个值。 添加操作可以使用以下代码: ``` ObjectNode objectNode = (ObjectNode) jsonNode; objectNode.put("address", "北京市海淀区"); ``` 其中,ObjectNode是JsonNode的子类,表示JSON中的一个对象。put方法可以向对象中添加一个键值对。 删除操作可以使用以下代码: ``` ObjectNode objectNode = (ObjectNode) jsonNode; objectNode.remove("hobby"); ``` 其中,remove方法可以删除对象中指定的键值对。 更新操作可以使用以下代码: ``` ObjectNode objectNode = (ObjectNode) jsonNode; objectNode.put("age", 21); ``` 其中,put方法可以更新对象中指定键的值。 最后,将更新后的JSON序列化为字符串,可以使用以下代码: ``` String updatedJsonString = objectMapper.writeValueAsString(jsonNode); System.out.println(updatedJsonString); ``` 完整的代码如下: ``` import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; public class JsonUtils { public static void main(String[] args) throws Exception { String jsonString = "{\"name\":\"张三\",\"age\":20,\"gender\":\"男\",\"hobby\":[\"篮球\",\"游泳\"]}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(jsonString); // 添加操作 ObjectNode objectNode = (ObjectNode) jsonNode; objectNode.put("address", "北京市海淀区"); // 删除操作 objectNode.remove("hobby"); // 更新操作 objectNode.put("age", 21); String updatedJsonString = objectMapper.writeValueAsString(jsonNode); System.out.println(updatedJsonString); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_43648977

原创

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值