DataTools.ConvertObjectToJson.java Source code

Java tutorial

Introduction

Here is the source code for DataTools.ConvertObjectToJson.java

Source

package DataTools;

import Data.Storage;
import StorageHelper.Converter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.joda.JodaMapper;
import org.joda.time.DateTime;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Iterator;

/**
 Copyright 2016 Alianza 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.
    
 */

/**
Generates various types of randomized unique data
 */
public class ConvertObjectToJson {

    /**
     * Converts a data model into a JSONObject
     * @param model Data model to be converted
     * @return JSONObject
     */
    public <T> JSONObject convertToJson(T model) {
        //is already do nothing,  all invalid
        if (model instanceof JSONObject || model instanceof JSONArray) {
            return null;
        }
        ObjectMapper mapper = new ObjectMapper();
        JSONObject json = null;

        addCustomSerializing(mapper);

        try {
            String jsonString = mapper.writeValueAsString(model);
            //conversion not working, get out of here!
            if (Utils.isJSONObject(jsonString)) {
                json = new JSONObject(jsonString);
                json = removeNull(json);
            }
        } catch (JSONException | JsonProcessingException e) {
            e.printStackTrace();
        }
        return json;
    }

    public static Object convertStringToObject(String data) {
        String tempValue = data.trim();
        Object value = data;
        try {
            if (Utils.isJsonArray(data))
                value = new JSONArray(tempValue);
            else if (Utils.isJSONObject(tempValue))
                value = new JSONObject(tempValue);
            else if (Utils.isXml(tempValue)) {
                String xmlValue = Converter.cleanXmlHeader(tempValue);
                if (xmlValue.startsWith("<html>") && xmlValue.endsWith("</html>")) {
                    value = xmlValue;
                } else {
                    value = Converter.cleanXml(xmlValue);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return value;
    }

    public static <R> R convertToObject(String json, Class<R> type) {
        R mapped = null;
        JodaMapper mapper = new JodaMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
                .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
        try {
            mapped = mapper.readValue(json, type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mapped;
    }

    /**
     * add the datetime object in correct format
     * date objects come out all messed up
     * change them to a string of the date
     */
    public static String cleanupDate(DateTime date) {
        return date.toString().split("T")[0];
    }

    /**
     * add the datetime object in correct format
     * date objects come out all messed up
     * change them to a string of the date
     */
    public static String cleanupDate(ZonedDateTime date) {
        return date.toString().split("T")[0];
    }

    /**
     * If the key or value of a JSONObject is null, remove that key (recursive function for JSONObjects within JSONObjects)
     * @param json JSONObject to remove null from
     * @return JSONObject
     */
    private JSONObject removeNull(JSONObject json) {
        Iterator<String> keys = null;

        try {
            keys = new JSONObject(json.toString()).keys();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //full json has null for non populated data, we just remove those
        for (String key : iterable(keys)) {
            try {
                if (json.isNull(key) || json.getString(key).equals("null") || json.getString(key).equals("{}"))
                    json.remove(key);

                //handle recursive json objects, both objects and arrays
                else if (json.getString(key).startsWith("{") && json.getString(key).endsWith("}")) {
                    json.put(key, removeNull(new JSONObject(json.getString(key))));
                } else if (json.getString(key).startsWith("[") && json.getString(key).endsWith("]")) {
                    json.put(key, removeNull(new JSONArray(json.getString(key))));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return json;
    }

    private JSONArray removeNull(JSONArray json) {
        //create a new jsonArray
        JSONArray newArray = new JSONArray();
        for (int i = 0; i < json.length(); ++i) {
            try {
                //if its null and not an object then remove it
                if (!(json.isNull(i) || json.getString(i).equals("null") || json.getString(i).equals("{}"))
                        && !Utils.isJSONObject(json.getString(i)) && !Utils.isJsonArray(json.getString(i))) {
                    newArray.put(json.get(i));
                }

                //handle recursive json objects, both objects and arrays
                else if (json.getString(i).startsWith("{") && json.getString(i).endsWith("}")) {
                    newArray.put(removeNull(new JSONObject(json.getString(i))));
                } else if (json.getString(i).startsWith("[") && json.getString(i).endsWith("]")) {
                    newArray.put(removeNull(new JSONArray(json.getString(i))));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return newArray;
    }

    private void addCustomSerializing(ObjectMapper mapper) {
        //custom serializer to help parsing dates
        class dateSerializer extends JsonSerializer<DateTime> {
            @Override
            public void serialize(DateTime dateTime, JsonGenerator jsonGenerator,
                    SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString(cleanupDate(dateTime));
            }
        }

        //custom serializer to help parsing dates
        class zoneDateSerializer extends JsonSerializer<ZonedDateTime> {
            @Override
            public void serialize(ZonedDateTime dateTime, JsonGenerator jsonGenerator,
                    SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString(cleanupDate(dateTime));
            }
        }

        class utilDateSerializer extends JsonSerializer<Date> {
            @Override
            public void serialize(Date dateTime, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
                    throws IOException {
                jsonGenerator.writeString(dateTime.toString());
            }
        }

        class JsonObjectSerializer extends JsonSerializer<JSONObject> {
            @Override
            public void serialize(JSONObject jsonObject, JsonGenerator jsonGenerator,
                    SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeString(jsonObject.toString());
            }
        }
        class JsonArraySerializer extends JsonSerializer<JSONArray> {
            @Override
            public void serialize(JSONArray jsonArray, JsonGenerator jsonGenerator,
                    SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeString(jsonArray.toString());
            }
        }
        class StorageSerializer extends JsonSerializer<Storage> {
            @Override
            public void serialize(Storage storage, JsonGenerator jsonGenerator,
                    SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeString(storage.toString());
            }
        }

        //setup new serializer
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(DateTime.class, new dateSerializer());
        simpleModule.addSerializer(ZonedDateTime.class, new zoneDateSerializer());
        simpleModule.addSerializer(Date.class, new utilDateSerializer());
        simpleModule.addSerializer(JSONObject.class, new JsonObjectSerializer());
        simpleModule.addSerializer(JSONArray.class, new JsonArraySerializer());
        simpleModule.addSerializer(Storage.class, new StorageSerializer());
        mapper.registerModule(simpleModule);
    }

    /**
     * Used for looping through json keys
     * @param it
     * @param <T>
     * @return it
     */
    private static <T> Iterable<T> iterable(final Iterator<T> it) {
        return () -> it;
    }
}