com.formkiq.vision.util.JSONBuilder Maven / Gradle / Ivy
/*
* Copyright (C) 2018 FormKiQ 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 com.formkiq.vision.util;
import java.io.IOException;
import java.text.SimpleDateFormat;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
*
* JSON Builder Helper Methods.
*
*/
public class JSONBuilder {
/**
* {@link Object} to JSON.
* @param obj {@link Object}
* @return {@link String}
* @throws IOException IOException
*/
public String toJSON(final Object obj) throws IOException {
return build().writeValueAsString(obj);
}
/**
* {@link Object} to JSON.
* @param obj {@link Object}
* @return {@link String}
* @throws IOException IOException
*/
public String toJSONPretty(final Object obj) throws IOException {
return build().writerWithDefaultPrettyPrinter().writeValueAsString(obj);
}
/**
* @return {@link ObjectMapper}
*/
private ObjectMapper build() {
ObjectMapper om = new ObjectMapper();
om.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
om.setDateFormat(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"));
om.setPropertyNamingStrategy(PropertyNamingStrategy.LOWER_CASE);
om.setSerializationInclusion(Include.NON_NULL);
om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
om.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
return om;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy