Example usage for com.google.gson JsonElement isJsonPrimitive

List of usage examples for com.google.gson JsonElement isJsonPrimitive

Introduction

In this page you can find the example usage for com.google.gson JsonElement isJsonPrimitive.

Prototype

public boolean isJsonPrimitive() 

Source Link

Document

provides check for verifying if this element is a primitive or not.

Usage

From source file:fr.inria.atlanmod.discoverer.JsonDiscoverer.java

License:Open Source License

/**
 * Maps json types into ecore types/*  w w  w.  j  a v  a 2s.  c om*/
 * 
 * @param id
 * @param value
 * @return
 */
private EClassifier mapType(String id, JsonElement value) {
    if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) {
        return EcorePackage.Literals.ESTRING;
    } else if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber()) {
        return EcorePackage.Literals.EINT;
    } else if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isBoolean()) {
        return EcorePackage.Literals.EBOOLEAN;
    } else if (value.isJsonArray()) {
        JsonArray arrayValue = value.getAsJsonArray();
        if (arrayValue.size() > 0) {
            EClassifier generalArrayType = mapType(digestId(id), arrayValue.get(0));
            for (int i = 1; i < arrayValue.size(); i++) {
                JsonElement arrayElement = arrayValue.get(i);
                EClassifier arrayType = mapType(digestId(id), arrayElement);
                if (generalArrayType != arrayType) {
                    LOGGER.finer(
                            "[mapType] Detected array multi-typed, using fallback type (String) for " + id);
                    return EcorePackage.Literals.ESTRING;
                }
            }
            return generalArrayType;
        }
    } else if (value.isJsonObject()) {
        return discoverMetaclass(digestId(id), value.getAsJsonObject());
    }
    LOGGER.finer("[mapType] Type not discovererd for " + id);
    return EcorePackage.Literals.ESTRING;
}

From source file:fr.inria.atlanmod.discoverer.JsonMultiInjector.java

License:Open Source License

protected Object digestValue(JsonElement value) {
    if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) {
        return value.getAsJsonPrimitive().getAsString();
    } else if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber()) {
        return new Integer(value.getAsJsonPrimitive().getAsNumber().intValue());
    } else if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isBoolean()) {
        return value.getAsJsonPrimitive().getAsBoolean() ? Boolean.TRUE : Boolean.FALSE;
    } else {//from w  w  w. j  av a  2s  . co  m
        return null;
    }
}

From source file:fr.zcraft.MultipleInventories.snaphots.ItemStackSnapshot.java

License:Open Source License

/**
 * From a JSON element, constructs a data structure representing
 * the same structure (recursively) using native types.
 *
 * <p>We had to re-implement this to ensure the generated structure to have the
 * right data type (instead of all numbers being doubles) and precision.</p>
 *
 * @param element The json element to be decoded.
 * @return A native data structure (either a {@link Map Map&lt;String, Object&gt;},
 * a {@link List List&lt;Object&gt;}, or a native type) representing the same
 * structure (recursively)./*from   w w w  . ja  v a 2  s.  c o m*/
 *
 * @see #jsonToNative(JsonObject) Converts a json object to an explicit {@link Map}.
 * The JavaDoc also contains explainations on why this is needed.
 */
private static Object jsonToNative(final JsonElement element) {
    if (element.isJsonObject()) {
        return jsonToNative(element.getAsJsonObject());
    } else if (element.isJsonArray()) {
        final List<Object> list = new ArrayList<>();

        element.getAsJsonArray().forEach(listElement -> {
            final Object nativeValue = jsonToNative(listElement);

            if (nativeValue != null) {
                list.add(nativeValue);
            }
        });

        return list;
    } else if (element.isJsonPrimitive()) {
        final JsonPrimitive primitive = element.getAsJsonPrimitive();

        if (primitive.isBoolean()) {
            return primitive.getAsBoolean();
        } else if (primitive.isString()) {
            return primitive.getAsString();
        } else /* it's a number we yet have to find the type. */
        {
            final BigDecimal number = primitive.getAsBigDecimal();

            try {
                return number.byteValueExact();
            } catch (final ArithmeticException e1) {
                try {
                    return number.shortValueExact();
                } catch (final ArithmeticException e2) {
                    try {
                        return number.intValueExact();
                    } catch (final ArithmeticException e3) {
                        try {
                            return number.longValueExact();
                        } catch (final ArithmeticException e4) {
                            try {
                                return number.doubleValue();
                            } catch (final ArithmeticException | NumberFormatException e5) {
                                return number;
                            }
                        }
                    }
                }
            }
        }
    }

    // Else the element is null.
    return null;
}

From source file:funf.config.DefaultRuntimeTypeAdapterFactory.java

License:Open Source License

@SuppressWarnings("unchecked")
public static <T> Class<? extends T> getRuntimeType(JsonElement el, Class<T> baseClass,
        Class<? extends T> defaultClass) {
    Class<? extends T> type = defaultClass;
    String typeString = null;/*w  w  w. j ava2s  . co  m*/
    if (el != null) {
        try {
            if (el.isJsonObject()) {
                JsonObject jsonObject = el.getAsJsonObject();
                if (jsonObject.has(RuntimeTypeAdapterFactory.TYPE)) {
                    typeString = jsonObject.get(RuntimeTypeAdapterFactory.TYPE).getAsString();
                }
            } else if (el.isJsonPrimitive()) {
                typeString = el.getAsString();
            }
        } catch (ClassCastException e) {
        }
    }
    // TODO: expand string to allow for builtin to be specified as ".SampleProbe"
    if (typeString != null) {
        try {
            Class<?> runtimeClass = Class.forName(typeString);
            if (baseClass.isAssignableFrom(runtimeClass)) {
                type = (Class<? extends T>) runtimeClass;
            } else {
                Log.w(LogUtil.TAG, "RuntimeTypeAdapter: Runtime class '" + typeString
                        + "' is not assignable from default class '" + defaultClass.getName() + "'.");
            }
        } catch (ClassNotFoundException e) {
            Log.w(LogUtil.TAG, "RuntimeTypeAdapter: Runtime class '" + typeString + "' not found.");
        }
    }
    return type;
}

From source file:funfinabox.app.Info.java

License:Open Source License

private void reloadProbeList() {
    // Load probe list view from config
    if (pipeline != null && pipeline instanceof BasicPipeline) {
        List<String> names = new ArrayList<String>();
        for (JsonElement el : ((BasicPipeline) pipeline).getDataRequests()) {
            String probeClassName = el.isJsonPrimitive() ? el.getAsString()
                    : el.getAsJsonObject().get(RuntimeTypeAdapterFactory.TYPE).getAsString();
            DisplayName probeDisplayName = null;
            try {
                probeDisplayName = Class.forName(probeClassName).getAnnotation(DisplayName.class);
            } catch (ClassNotFoundException e) {

            }/*from w ww  .ja v  a  2s .co m*/
            String name = "Unknown";
            if (probeDisplayName == null) {
                String[] parts = probeClassName.split("\\.");
                if (parts.length == 0) {
                    Log.d(LogUtil.TAG, "Bad probe type: '" + probeClassName + "'");
                } else {
                    name = parts[parts.length - 1].replace("Probe", "");
                }
            } else {
                name = probeDisplayName.value();
            }
            names.add(name);
        }
        ((TextView) findViewById(R.id.probe_list)).setText(StringUtil.join(names, ", "));
    } else {
        ((TextView) findViewById(R.id.probe_list)).setText("Unknown...");
    }

}

From source file:gittest.API.java

public static HashMap<String, Object> createHashMapFromJsonString(String json) {

    JsonObject object = (JsonObject) parser.parse(json);
    Set<Map.Entry<String, JsonElement>> set = object.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator();
    HashMap<String, Object> map = new HashMap<String, Object>();

    while (iterator.hasNext()) {

        Map.Entry<String, JsonElement> entry = iterator.next();
        String key = entry.getKey();
        JsonElement value = entry.getValue();

        if (null != value) {
            if (!value.isJsonPrimitive()) {
                if (value.isJsonObject()) {

                    map.put(key, createHashMapFromJsonString(value.toString()));
                } else if (value.isJsonArray() && value.toString().contains(":")) {

                    List<HashMap<String, Object>> list = new ArrayList<>();
                    JsonArray array = value.getAsJsonArray();
                    if (null != array) {
                        for (JsonElement element : array) {
                            list.add(createHashMapFromJsonString(element.toString()));
                        }//from   w  w w. j  a v a  2s.c  om
                        map.put(key, list);
                    }
                } else if (value.isJsonArray() && !value.toString().contains(":")) {
                    map.put(key, value.getAsJsonArray());
                }
            } else {
                map.put(key, value.getAsString());
            }
        }
    }

    return map;
}

From source file:gobblin.util.dataset.DatasetUtils.java

License:Apache License

/**
 * Given a {@link Iterable} of dataset identifiers (e.g., name, URN, etc.), return a {@link Map} that links each
 * dataset with the extra configuration information specified in the state via {@link #DATASET_SPECIFIC_PROPS}.
 *///from w  ww . ja  v a2 s.co m
public static Map<String, State> getDatasetSpecificProps(Iterable<String> datasets, State state) {
    if (!Strings.isNullOrEmpty(state.getProp(DATASET_SPECIFIC_PROPS))
            || !Strings.isNullOrEmpty(state.getProp(KAFKA_TOPIC_SPECIFIC_STATE))) {
        Map<String, State> datasetSpecificConfigMap = Maps.newHashMap();

        JsonArray array = !Strings.isNullOrEmpty(state.getProp(DATASET_SPECIFIC_PROPS))
                ? state.getPropAsJsonArray(DATASET_SPECIFIC_PROPS)
                : state.getPropAsJsonArray(KAFKA_TOPIC_SPECIFIC_STATE);

        // Iterate over the entire JsonArray specified by the config key
        for (JsonElement datasetElement : array) {

            // Check that each entry in the JsonArray is a JsonObject
            Preconditions.checkArgument(datasetElement.isJsonObject(),
                    "The value for property " + DATASET_SPECIFIC_PROPS + " is malformed");
            JsonObject object = datasetElement.getAsJsonObject();

            // Only process JsonObjects that have a dataset identifier
            if (object.has(DATASET)) {
                JsonElement datasetNameElement = object.get(DATASET);
                Preconditions.checkArgument(datasetNameElement.isJsonPrimitive(), "The value for property "
                        + DATASET_SPECIFIC_PROPS + " is malformed, the " + DATASET + " field must be a string");

                // Iterate through each dataset that matches the value of the JsonObjects DATASET field
                for (String dataset : Iterables.filter(datasets,
                        new DatasetPredicate(datasetNameElement.getAsString()))) {

                    // If an entry already exists for a dataset, add it to the current state, else create a new state
                    if (datasetSpecificConfigMap.containsKey(dataset)) {
                        datasetSpecificConfigMap.get(dataset)
                                .addAll(StateUtils.jsonObjectToState(object, DATASET));
                    } else {
                        datasetSpecificConfigMap.put(dataset, StateUtils.jsonObjectToState(object, DATASET));
                    }
                }
            } else {
                LOG.warn("Skipping JsonElement " + datasetElement
                        + " as it is does not contain a field with key " + DATASET);
            }
        }
        return datasetSpecificConfigMap;
    }
    return Maps.newHashMap();
}

From source file:gsonlib.GsonRecursive.java

public static void makeRecursive(JsonElement ele) {
    JsonObject jsonObj = ele.getAsJsonObject();

    Set<Map.Entry<String, JsonElement>> entrySet = jsonObj.entrySet();
    for (Map.Entry<String, JsonElement> innerSet : entrySet) {
        String key = innerSet.getKey();

        JsonElement value = innerSet.getValue();

        if (value.isJsonObject()) {

            recXpathVal += key + "/";
            makeRecursive(value);//from   ww  w.ja  va2  s. c om
            recXpathVal = getSubstringToParent(recXpathVal) + "/";
        } else if (value.isJsonArray()) {
            JsonArray jArray = value.getAsJsonArray();
            for (int i = 0; i < jArray.size(); i++) {
                JsonElement arrEle = jArray.get(i);
                recXpathVal += key + "[" + (i + 1) + "]/";
                if (arrEle.isJsonObject()) {
                    makeRecursive(arrEle);

                } else if (arrEle.isJsonPrimitive()) {
                    put(recXpathVal, arrEle.getAsString());

                }
                recXpathVal = getSubstringToParent(recXpathVal) + "/";

            }

        } else if (value.isJsonPrimitive()) {
            recXpathVal += key + "/";

            put(recXpathVal.toString(), value.getAsString());
            recXpathVal = getSubstringToParent(recXpathVal) + "/";

        }

    }

}

From source file:gsonlib.GsonTransfer.java

public static void transferJsonResponseParamMap(JsonObject inJson, JsonObject outJson,
        Map<String, String> ctxMap) {

    Set<Map.Entry<String, JsonElement>> inJsonEntrySet = inJson.entrySet();

    for (Map.Entry<String, JsonElement> inJsonEntry : inJsonEntrySet) {
        String inJsonEntryKey = inJsonEntry.getKey();
        JsonElement inJsonEntryValue = inJsonEntry.getValue();

        JsonElement outJsonEntryValue = outJson.get(inJsonEntryKey);

        if (outJsonEntryValue != null) {
            if (inJsonEntryValue.isJsonPrimitive() && outJsonEntryValue.isJsonPrimitive()) {
                JsonPrimitive inPrimitive = inJsonEntryValue.getAsJsonPrimitive();
                JsonPrimitive outPrimitive = outJsonEntryValue.getAsJsonPrimitive();
                ctxMap.put(inPrimitive.getAsString(), outPrimitive.getAsString());
            } else if (inJsonEntryValue.isJsonObject() && outJsonEntryValue.isJsonObject()) {
                JsonObject outJsonEntryValObj = outJsonEntryValue.getAsJsonObject();
                JsonObject inJsonEntryValObj = inJsonEntryValue.getAsJsonObject();
                transferJsonResponseParamMap(inJsonEntryValObj, outJsonEntryValObj, ctxMap);
            } else if (inJsonEntryValue.isJsonArray() && outJsonEntryValue.isJsonArray()) {
                JsonArray inJsonEntryValArr = inJsonEntryValue.getAsJsonArray();
                JsonArray outJsonEntryValArr = outJsonEntryValue.getAsJsonArray();
                int outSize = outJsonEntryValArr.size();
                for (int i = 0; i < inJsonEntryValArr.size(); i++) {
                    if (outSize > i) {
                        JsonElement inArrEle = inJsonEntryValArr.get(i);
                        JsonElement outArrEle = outJsonEntryValArr.get(i);
                        if (inArrEle.isJsonPrimitive() && outArrEle.isJsonPrimitive()) {
                            JsonPrimitive inPrimitive = inArrEle.getAsJsonPrimitive();
                            JsonPrimitive outPrimitive = outArrEle.getAsJsonPrimitive();
                            ctxMap.put(inPrimitive.getAsString(), outPrimitive.getAsString());
                        } else if (inArrEle.isJsonObject() && outArrEle.isJsonObject()) {
                            JsonObject outJsonEntryValObj = outArrEle.getAsJsonObject();
                            JsonObject inJsonEntryValObj = inArrEle.getAsJsonObject();
                            transferJsonResponseParamMap(inJsonEntryValObj, outJsonEntryValObj, ctxMap);
                        }/*  ww w .j a v a2  s  .  com*/
                    }
                }
            }
        }

    }

}

From source file:guru.qas.martini.report.column.ExceptionColumn.java

License:Apache License

@Override
public void addResult(State state, Cell cell, JsonObject o) {
    JsonArray array = o.getAsJsonArray(KEY_STEPS);
    int size = array.size();

    String value = null;/*from  w  w  w .  java  2s.com*/
    for (int i = 0; null == value && i < size; i++) {
        JsonElement element = array.get(i);
        JsonObject step = element.getAsJsonObject();
        JsonElement keyElement = step.get(KEY_EXCEPTION);
        JsonPrimitive primitive = null != keyElement && keyElement.isJsonPrimitive()
                ? keyElement.getAsJsonPrimitive()
                : null;
        String stackTrace = null == primitive ? null : primitive.getAsString().trim();
        value = null != stackTrace && !stackTrace.isEmpty() ? stackTrace : null;
    }

    RichTextString richTextString = new XSSFRichTextString(value);
    cell.setCellValue(richTextString);
}