Example usage for com.google.gson JsonElement isJsonObject

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

Introduction

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

Prototype

public boolean isJsonObject() 

Source Link

Document

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

Usage

From source file:EAIJSONConverter.java

License:Open Source License

public static SiebelPropertySet JsonObjectToPropertySet(JsonObject obj, SiebelPropertySet ps) {
    Iterator<Entry<String, JsonElement>> iterator = obj.entrySet().iterator();
    SiebelPropertySet child;// w w  w  .  j  a v  a  2s. c om
    while (iterator.hasNext()) {
        JsonArray jsonArray = new JsonArray();
        JsonObject jsonObject = new JsonObject();
        Map.Entry mapEntry = (Map.Entry) iterator.next();
        if (mapEntry != null) {
            JsonElement jsonelement = (JsonElement) mapEntry.getValue();
            if (jsonelement.isJsonArray()) {
                jsonArray = jsonelement.getAsJsonArray();
                child = new SiebelPropertySet();
                child.setType("ListOf-" + mapEntry.getKey().toString());
                for (int i = 0; i < jsonArray.size(); i++) {
                    if (jsonArray.get(i).isJsonObject() || jsonArray.get(i).isJsonArray()) {
                        SiebelPropertySet temp = new SiebelPropertySet();
                        temp.setType("" + i);
                        if (jsonArray.get(i).isJsonObject())
                            child.addChild(JsonObjectToPropertySet(jsonArray.get(i).getAsJsonObject(), temp));
                        else {
                            JsonObject aux = new JsonObject();
                            aux.add("" + i, jsonArray.get(i));
                            child.addChild(JsonObjectToPropertySet(aux, temp));

                        }
                    } else
                        child.setProperty("" + i, jsonArray.get(i).getAsString());
                }
                ps.addChild(child);
            } else if (jsonelement.isJsonObject()) {
                jsonObject = jsonelement.getAsJsonObject();
                child = new SiebelPropertySet();
                child.setType(mapEntry.getKey().toString());
                ps.addChild(JsonObjectToPropertySet(jsonObject, child));
            } else {
                ps.setProperty(mapEntry.getKey().toString(), mapEntry.getValue().toString());
            }
        }
    }

    return ps;
}

From source file:ambari.interaction.NodeController.java

public static ArrayList<ComponentInformation> getListOfNodes() throws Exception {
    String url = "http://127.0.0.1:8080/api/v1/clusters/mycluster/services/HDFS/components/DATANODE?fields=host_components/HostRoles/desired_admin_state,host_components/HostRoles/state";
    String responseJson = HttpURLConnectionExample.sendGet(url);
    System.out.print(responseJson);
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonTree = jsonParser.parse(responseJson);
    ArrayList<ComponentInformation> listOfCompoents = new ArrayList<ComponentInformation>();

    if (jsonTree.isJsonObject()) {
        JsonObject jsonObject = jsonTree.getAsJsonObject();
        JsonElement hostComponents = jsonObject.get("host_components");

        if (hostComponents.isJsonArray()) {
            JsonArray hostComponentsJsonArray = hostComponents.getAsJsonArray();
            System.out.println("\nStart");
            System.out.println(hostComponentsJsonArray);

            for (int i = 0; i < hostComponentsJsonArray.size(); i++) {
                JsonElement hostComponentsElem = hostComponentsJsonArray.get(i);

                if (hostComponentsElem.isJsonObject()) {
                    JsonObject jsonObjectElem = hostComponentsElem.getAsJsonObject();
                    JsonElement hostRolesElem = jsonObjectElem.get("HostRoles");

                    if (hostRolesElem.isJsonObject()) {
                        JsonObject hostRolesObjs = hostRolesElem.getAsJsonObject();
                        JsonElement componentNameElem = hostRolesObjs.get("component_name");
                        JsonElement hostNameElem = hostRolesObjs.get("host_name");
                        JsonElement stateElem = hostRolesObjs.get("state");

                        listOfCompoents.add(new ComponentInformation(componentNameElem.toString(),
                                hostNameElem.toString(), stateElem.toString()));
                    }/*from  w  w w  .j ava 2 s. c  om*/
                }
            }
        }
    }

    return listOfCompoents;
}

From source file:angularBeans.remote.InvocationHandler.java

License:LGPL

private void update(Object o, JsonObject params) {

    if (params != null) {

        // boolean firstIn = false;

        for (Map.Entry<String, JsonElement> entry : params.entrySet()) {

            JsonElement value = entry.getValue();
            String name = entry.getKey();

            if ((name.equals("sessionUID")) || (name.equals("args"))) {
                continue;
            }//from   ww w.  j a  v a 2  s.c  o  m

            if ((value.isJsonObject()) && (!value.isJsonNull())) {

                String getName;
                try {
                    getName = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name));

                    Method getter = o.getClass().getMethod(getName);

                    Object subObj = getter.invoke(o);

                    // logger.log(Level.INFO, "#entring sub object "+name);
                    update(subObj, value.getAsJsonObject());

                } catch (NoSuchFieldException | SecurityException | IllegalAccessException
                        | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) {

                    e.printStackTrace();
                }

            }
            // ------------------------------------
            if (value.isJsonArray()) {

                try {
                    String getter = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name));

                    Method get = o.getClass().getDeclaredMethod(getter);

                    Type type = get.getGenericReturnType();
                    ParameterizedType pt = (ParameterizedType) type;
                    Type actType = pt.getActualTypeArguments()[0];

                    String className = actType.toString();

                    className = className.substring(className.indexOf("class") + 6);
                    Class clazz = Class.forName(className);

                    JsonArray array = value.getAsJsonArray();

                    Collection collection = (Collection) get.invoke(o);
                    Object elem;
                    for (JsonElement element : array) {
                        if (element.isJsonPrimitive()) {
                            JsonPrimitive primitive = element.getAsJsonPrimitive();

                            elem = element;
                            if (primitive.isBoolean())
                                elem = primitive.getAsBoolean();
                            if (primitive.isString()) {
                                elem = primitive.getAsString();
                            }
                            if (primitive.isNumber())
                                elem = primitive.isNumber();

                        } else {

                            elem = util.deserialise(clazz, element);
                        }

                        try {

                            if (collection instanceof List) {

                                if (collection.contains(elem))
                                    collection.remove(elem);
                            }

                            collection.add(elem);
                        } catch (UnsupportedOperationException e) {
                            Logger.getLogger("AngularBeans").log(java.util.logging.Level.WARNING,
                                    "trying to modify an immutable collection : " + name);
                        }

                    }

                } catch (Exception e) {
                    e.printStackTrace();

                }

            }

            // ------------------------------------------
            if (value.isJsonPrimitive() && (!name.equals("setSessionUID"))) {
                try {

                    if (!CommonUtils.hasSetter(o.getClass(), name)) {
                        continue;
                    }
                    name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1);

                    Class type = null;
                    for (Method set : o.getClass().getDeclaredMethods()) {
                        if (CommonUtils.isSetter(set)) {
                            if (set.getName().equals(name)) {
                                Class<?>[] pType = set.getParameterTypes();

                                type = pType[0];
                                break;

                            }
                        }

                    }

                    if (type.equals(LobWrapper.class))
                        continue;

                    Object param = null;
                    if ((params.entrySet().size() >= 1) && (type != null)) {

                        param = CommonUtils.convertFromString(value.getAsString(), type);

                    }

                    o.getClass().getMethod(name, type).invoke(o, param);

                } catch (Exception e) {
                    e.printStackTrace();

                }
            }

        }
    }

}

From source file:at.maui.cheapcast.json.deserializer.RampMessageDeserializer.java

License:Apache License

@Override
public RampMessage deserialize(JsonElement jsonElement, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    if (jsonElement.isJsonObject()) {
        JsonObject obj = jsonElement.getAsJsonObject();
        String t = obj.getAsJsonPrimitive("type").getAsString();

        if (t.equals("VOLUME")) {
            return jsonDeserializationContext.deserialize(jsonElement, RampVolume.class);
        } else if (t.equals("STATUS") || t.equals("RESPONSE")) {
            return jsonDeserializationContext.deserialize(jsonElement, RampStatus.class);
        } else if (t.equals("PLAY")) {
            return jsonDeserializationContext.deserialize(jsonElement, RampPlay.class);
        } else if (t.equals("STOP")) {
            return jsonDeserializationContext.deserialize(jsonElement, RampStop.class);
        } else if (t.equals("LOAD")) {
            return jsonDeserializationContext.deserialize(jsonElement, RampLoad.class);
        } else if (t.equals("INFO")) {
            return jsonDeserializationContext.deserialize(jsonElement, RampInfo.class);
        }//w  ww  . j  a v  a 2  s  .  c om
        Log.w(LOG_TAG, "Ramp message not handle : " + t);
    }

    return null;
}

From source file:at.orz.arangodb.impl.InternalDocumentDriverImpl.java

License:Apache License

private <T> DocumentEntity<T> _createDocument(String database, String collectionName, String documentKey,
        Object value, Boolean createCollection, Boolean waitForSync, boolean raw) throws ArangoException {

    validateCollectionName(collectionName);

    String body;//from   ww w. j  a va  2  s  .  c  om
    if (raw) {
        body = value.toString();
    } else if (documentKey != null) {
        JsonElement elem = EntityFactory.toJsonElement(value, false);
        if (elem.isJsonObject()) {
            elem.getAsJsonObject().addProperty("_key", documentKey);
        }
        body = EntityFactory.toJsonString(elem);
    } else {
        body = EntityFactory.toJsonString(value);
    }

    HttpResponseEntity res = httpManager.doPost(createEndpointUrl(baseUrl, database, "/_api/document"),
            new MapBuilder().put("collection", collectionName).put("createCollection", createCollection)
                    .put("waitForSync", waitForSync).get(),
            body);

    return createEntity(res, DocumentEntity.class);

}

From source file:at.orz.arangodb.impl.InternalGraphDriverImpl.java

License:Apache License

public <T> EdgeEntity<T> createEdge(String database, String graphName, String key, String fromHandle,
        String toHandle, Object value, String label, Boolean waitForSync) throws ArangoException {

    JsonObject obj;/*  w w  w  . j  a  v a  2 s . c  o  m*/
    if (value == null) {
        obj = new JsonObject();
    } else {
        JsonElement elem = EntityFactory.toJsonElement(value, false);
        if (elem.isJsonObject()) {
            obj = elem.getAsJsonObject();
        } else {
            throw new IllegalArgumentException("value need object type(not support array, primitive, etc..).");
        }
    }
    obj.addProperty("_key", key);
    obj.addProperty("_from", fromHandle);
    obj.addProperty("_to", toHandle);
    obj.addProperty("$label", label);

    validateCollectionName(graphName);
    HttpResponseEntity res = httpManager.doPost(
            createEndpointUrl(baseUrl, database, "/_api/graph", StringUtils.encodeUrl(graphName), "/edge"),
            new MapBuilder().put("waitForSync", waitForSync).get(), EntityFactory.toJsonString(obj));

    return createEntity(res, EdgeEntity.class, value == null ? null : value.getClass());

}

From source file:bind.JsonTreeReader.java

License:Apache License

@Override
public JsonToken peek() throws IOException {
    if (stack.isEmpty()) {
        return JsonToken.END_DOCUMENT;
    }/*from  w  ww. ja  v a  2  s. c o  m*/

    Object o = peekStack();
    if (o instanceof Iterator) {
        Object secondToTop = stack.get(stack.size() - 2);
        boolean isObject = secondToTop instanceof JsonElement && ((JsonElement) secondToTop).isJsonObject();
        Iterator<?> iterator = (Iterator<?>) o;
        if (iterator.hasNext()) {
            if (isObject) {
                return JsonToken.NAME;
            } else {
                stack.add(iterator.next());
                return peek();
            }
        } else {
            return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY;
        }
    } else if (o instanceof JsonElement) {
        JsonElement el = (JsonElement) o;
        if (el.isJsonObject()) {
            return JsonToken.BEGIN_OBJECT;
        } else if (el.isJsonArray()) {
            return JsonToken.BEGIN_ARRAY;
        } else if (el.isJsonPrimitive()) {
            JsonPrimitive primitive = (JsonPrimitive) o;
            if (primitive.isString()) {
                return JsonToken.STRING;
            } else if (primitive.isBoolean()) {
                return JsonToken.BOOLEAN;
            } else if (primitive.isNumber()) {
                return JsonToken.NUMBER;
            } else {
                throw new AssertionError();
            }
        } else if (el.isJsonNull()) {
            return JsonToken.NULL;
        }
        throw new AssertionError();
    } else if (o == SENTINEL_CLOSED) {
        throw new IllegalStateException("JsonReader is closed");
    } else {
        throw new AssertionError();
    }
}

From source file:bind.JsonTreeWriter.java

License:Apache License

@Override
public JsonWriter endObject() throws IOException {
    if (stack.isEmpty() || pendingName != null) {
        throw new IllegalStateException();
    }// w w w .  j av a2  s  .  c om
    JsonElement element = peek();
    if (element.isJsonObject()) {
        stack.remove(stack.size() - 1);
        return this;
    }
    throw new IllegalStateException();
}

From source file:bind.JsonTreeWriter.java

License:Apache License

@Override
public JsonWriter name(String name) throws IOException {
    if (stack.isEmpty() || pendingName != null) {
        throw new IllegalStateException();
    }/*from  w  w  w .  j  ava 2 s  .c o m*/
    JsonElement element = peek();
    if (element.isJsonObject()) {
        pendingName = name;
        return this;
    }
    throw new IllegalStateException();
}

From source file:blusunrize.immersiveengineering.client.models.multilayer.MultiLayerModel.java

@Nonnull
@Override/*from w  w w.j  av a  2s  . c  o m*/
public IModel process(ImmutableMap<String, String> customData) {
    Map<BlockRenderLayer, List<ModelData>> newSubs = new HashMap<>();
    JsonParser parser = new JsonParser();
    Map<String, String> unused = new HashMap<>();
    for (String layerStr : customData.keySet())
        if (LAYERS_BY_NAME.containsKey(layerStr)) {

            BlockRenderLayer layer = LAYERS_BY_NAME.get(layerStr);
            JsonElement ele = parser.parse(customData.get(layerStr));
            if (ele.isJsonObject()) {
                ModelData data = ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                        ImmutableMap.of());
                newSubs.put(layer, ImmutableList.of(data));
            } else if (ele.isJsonArray()) {
                JsonArray array = ele.getAsJsonArray();
                List<ModelData> models = new ArrayList<>();
                for (JsonElement subEle : array)
                    if (subEle.isJsonObject())
                        models.add(ModelData.fromJson(ele.getAsJsonObject(), ImmutableList.of(),
                                ImmutableMap.of()));
                newSubs.put(layer, models);
            }
        } else
            unused.put(layerStr, customData.get(layerStr));
    JsonObject unusedJson = ModelData.asJsonObject(unused);
    for (Entry<BlockRenderLayer, List<ModelData>> entry : newSubs.entrySet())
        for (ModelData d : entry.getValue())
            for (Entry<String, JsonElement> entryJ : unusedJson.entrySet())
                if (!d.data.has(entryJ.getKey()))
                    d.data.add(entryJ.getKey(), entryJ.getValue());
    if (!newSubs.equals(subModels))
        return new MultiLayerModel(newSubs);
    return this;
}