org.apache.eventmesh.common.utils.JsonUtils Maven / Gradle / Ivy
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.eventmesh.common.utils;
import org.apache.eventmesh.common.Constants;
import org.apache.eventmesh.common.EventMeshDateFormat;
import org.apache.eventmesh.common.exception.JsonException;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.Map;
import java.util.Objects;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
/**
* Json serialize or deserialize utils.
*/
public class JsonUtils {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
OBJECT_MAPPER.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
OBJECT_MAPPER.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
OBJECT_MAPPER.setDateFormat(new EventMeshDateFormat(Constants.DATE_FORMAT_DEFAULT));
OBJECT_MAPPER.setSerializationInclusion(JsonInclude.Include.NON_NULL);
OBJECT_MAPPER.registerModule(new JavaTimeModule());
}
public static T convertValue(Object fromValue, Class toValueType) {
return OBJECT_MAPPER.convertValue(fromValue, toValueType);
}
public static T convertValue(Object fromValue, TypeReference toValueTypeRef) {
return OBJECT_MAPPER.convertValue(fromValue, toValueTypeRef);
}
public static T mapToObject(Map map, Class beanClass) {
if (map == null) {
return null;
}
Object obj = OBJECT_MAPPER.convertValue(map, beanClass);
return beanClass.cast(obj);
}
public static Map objectToMap(Object obj) {
if (obj == null) {
return null;
}
return OBJECT_MAPPER.convertValue(obj, new TypeReference
© 2015 - 2025 Weber Informatics LLC | Privacy Policy