All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.bdware.doip.cluster.engine.JsonUtil Maven / Gradle / Ivy

There is a newer version: 1.5.4
Show newest version
package org.bdware.doip.cluster.engine;

import com.google.gson.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class JsonUtil {
    static Logger LOGGER = LogManager.getLogger(JsonUtil.class);

    public JsonArray createJsonArray() {
        return new JsonArray();
    }

    public JsonObject createJsonObject() {
        return new JsonObject();
    }

    public String toString(Object obj) {
        return new Gson().toJson(obj);
    }

    public Object toJavaArray(JsonArray jsonArray) {
        if (jsonArray == null || jsonArray.size() == 0) {
            return null;
        }

        boolean allStrings = true;
        boolean allNumbers = true;
        for (JsonElement element : jsonArray) {
            if (!element.isJsonPrimitive()) {
                // If the element is not a primitive (e.g., JsonObject or JsonArray),
                // we can't reliably determine the common type, so return JsonElement[].
                JsonElement[] jsonElementArray = new JsonElement[jsonArray.size()];
                for (int i = 0; i < jsonArray.size(); i++) {
                    jsonElementArray[i] = jsonArray.get(i);
                }
                return jsonElementArray;
            }
            JsonPrimitive primitive = element.getAsJsonPrimitive();
            if (!primitive.isString()) {
                allStrings = false;
            }
            if (!primitive.isNumber()) {
                allNumbers = false;
            }
        }

        if (allStrings) {
            String[] stringArray = new String[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                stringArray[i] = jsonArray.get(i).getAsString();
            }
            return stringArray;
        } else if (allNumbers) {
            Number[] numberArray = new Number[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                numberArray[i] = jsonArray.get(i).getAsNumber();
            }
            return numberArray;
        } else {
            // If the array contains a mix of string and number primitives,
            // return JsonElement[] to preserve the original types.
            JsonElement[] jsonElementArray = new JsonElement[jsonArray.size()];
            for (int i = 0; i < jsonArray.size(); i++) {
                jsonElementArray[i] = jsonArray.get(i);
            }
            return jsonElementArray;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy