io.mantisrx.common.JsonSerializer Maven / Gradle / Ivy
/*
* Copyright 2022 Netflix, Inc.
*
* Licensed 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 io.mantisrx.common;
import io.mantisrx.shaded.com.fasterxml.jackson.core.type.TypeReference;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.DeserializationFeature;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.SerializationFeature;
import io.mantisrx.shaded.com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
import io.mantisrx.shaded.com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import java.io.IOException;
import java.util.Map;
public class JsonSerializer {
private static final ObjectMapper defaultObjectMapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false)
.registerModule(new Jdk8Module());
public static final SimpleFilterProvider DEFAULT_FILTER_PROVIDER;
static {
DEFAULT_FILTER_PROVIDER = new SimpleFilterProvider();
DEFAULT_FILTER_PROVIDER.setFailOnUnknownId(false);
}
public T fromJSON(String json, Class expectedType) throws IOException {
return defaultObjectMapper.readerFor(expectedType).readValue(json);
}
public T fromJson(byte[] json, Class expectedType) throws IOException {
return defaultObjectMapper.readValue(json, expectedType);
}
public T fromJSON(String json, TypeReference expectedType) throws IOException {
return defaultObjectMapper.readerFor(expectedType).readValue(json);
}
public String toJson(Object object) throws IOException {
return defaultObjectMapper.writeValueAsString(object);
}
public byte[] toJsonBytes(Object object) throws IOException {
return defaultObjectMapper.writeValueAsBytes(object);
}
public Map toMap(String json) throws IOException {
return defaultObjectMapper.readValue(json, new TypeReference