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:com.haulmont.cuba.core.app.importexport.EntityImportViewBuilder.java

License:Apache License

@Override
public EntityImportView buildFromJson(String json, MetaClass metaClass) {
    JsonParser jsonParser = new JsonParser();
    JsonElement rootElement = jsonParser.parse(json);
    if (!rootElement.isJsonObject()) {
        throw new RuntimeException("Passed json is not a JSON object");
    }/*from  w w  w  . ja  va2s  . co  m*/
    return buildFromJsonObject(rootElement.getAsJsonObject(), metaClass);
}

From source file:com.haulmont.cuba.core.app.importexport.EntityImportViewBuilder.java

License:Apache License

protected EntityImportView buildFromJsonObject(JsonObject jsonObject, MetaClass metaClass) {
    EntityImportView view = new EntityImportView(metaClass.getJavaClass());

    for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) {
        String propertyName = entry.getKey();
        MetaProperty metaProperty = metaClass.getProperty(propertyName);
        if (metaProperty != null) {
            Range propertyRange = metaProperty.getRange();
            Class<?> propertyType = metaProperty.getJavaType();
            if (propertyRange.isDatatype() || propertyRange.isEnum()) {
                if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                    view.addLocalProperty(propertyName);
            } else if (propertyRange.isClass()) {
                if (Entity.class.isAssignableFrom(propertyType)) {
                    if (metadataTools.isEmbedded(metaProperty)) {
                        MetaClass propertyMetaClass = metadata.getClass(propertyType);
                        JsonElement propertyJsonObject = entry.getValue();
                        if (!propertyJsonObject.isJsonObject()) {
                            throw new RuntimeException("JsonObject was expected for property " + propertyName);
                        }//  w  ww. j a v a  2s  . co m
                        if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) {
                            EntityImportView propertyImportView = buildFromJsonObject(
                                    propertyJsonObject.getAsJsonObject(), propertyMetaClass);
                            view.addEmbeddedProperty(propertyName, propertyImportView);
                        }
                    } else {
                        MetaClass propertyMetaClass = metadata.getClass(propertyType);
                        if (metaProperty.getType() == MetaProperty.Type.COMPOSITION) {
                            JsonElement propertyJsonObject = entry.getValue();
                            if (security.isEntityAttrUpdatePermitted(metaClass, propertyName)) {
                                if (propertyJsonObject.isJsonNull()) {
                                    //in case of null we must add such import behavior to update the reference with null value later
                                    if (metaProperty.getRange()
                                            .getCardinality() == Range.Cardinality.MANY_TO_ONE) {
                                        view.addManyToOneProperty(propertyName,
                                                ReferenceImportBehaviour.IGNORE_MISSING);
                                    } else {
                                        view.addOneToOneProperty(propertyName,
                                                ReferenceImportBehaviour.IGNORE_MISSING);
                                    }
                                } else {
                                    if (!propertyJsonObject.isJsonObject()) {
                                        throw new RuntimeException(
                                                "JsonObject was expected for property " + propertyName);
                                    }
                                    EntityImportView propertyImportView = buildFromJsonObject(
                                            propertyJsonObject.getAsJsonObject(), propertyMetaClass);
                                    if (metaProperty.getRange()
                                            .getCardinality() == Range.Cardinality.MANY_TO_ONE) {
                                        view.addManyToOneProperty(propertyName, propertyImportView);
                                    } else {
                                        view.addOneToOneProperty(propertyName, propertyImportView);
                                    }
                                }
                            }
                        } else {
                            if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                                if (metaProperty.getRange().getCardinality() == Range.Cardinality.MANY_TO_ONE) {
                                    view.addManyToOneProperty(propertyName,
                                            ReferenceImportBehaviour.ERROR_ON_MISSING);
                                } else {
                                    view.addOneToOneProperty(propertyName,
                                            ReferenceImportBehaviour.ERROR_ON_MISSING);
                                }
                        }
                    }
                } else if (Collection.class.isAssignableFrom(propertyType)) {
                    MetaClass propertyMetaClass = metaProperty.getRange().asClass();
                    switch (metaProperty.getRange().getCardinality()) {
                    case MANY_TO_MANY:
                        if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                            view.addManyToManyProperty(propertyName, ReferenceImportBehaviour.ERROR_ON_MISSING,
                                    CollectionImportPolicy.REMOVE_ABSENT_ITEMS);
                        break;
                    case ONE_TO_MANY:
                        if (metaProperty.getType() == MetaProperty.Type.COMPOSITION) {
                            JsonElement compositionJsonArray = entry.getValue();
                            if (!compositionJsonArray.isJsonArray()) {
                                throw new RuntimeException(
                                        "JsonArray was expected for property " + propertyName);
                            }
                            EntityImportView propertyImportView = buildFromJsonArray(
                                    compositionJsonArray.getAsJsonArray(), propertyMetaClass);
                            if (security.isEntityAttrUpdatePermitted(metaClass, propertyName))
                                view.addOneToManyProperty(propertyName, propertyImportView,
                                        CollectionImportPolicy.REMOVE_ABSENT_ITEMS);
                        }
                        break;
                    }
                }
            }
        }
    }

    return view;
}

From source file:com.hbm.devices.jet.JetPeer.java

License:Open Source License

@Override
public void update(Observable observable, Object obj) {
    try {/*from   w  w  w .  j ava  2s.  c  o m*/
        JsonElement element = parser.parse((String) obj);
        if (element == null) {
            return;
        }

        if (element.isJsonObject()) {
            handleSingleJsonMessage((JsonObject) element);
        } else if (element.isJsonArray()) {
            JsonArray array = (JsonArray) element;
            for (int i = 0; i < array.size(); i++) {
                JsonElement e = array.get(i);
                if (e.isJsonObject()) {
                    handleSingleJsonMessage((JsonObject) e);
                }
            }
        }
    } catch (JsonSyntaxException e) {
        /*
         * There is no error handling necessary in this case. If somebody sends us invalid JSON,
         * we just ignore the packet and go ahead.
         */
        LOGGER.log(Level.SEVERE, "Can't parse JSON!", e);
    }
}

From source file:com.helion3.prism.util.DataUtil.java

License:MIT License

/**
 * Attempts to convert a JsonElement to an a known type.
 *
 * @param element JsonElement/*from ww  w  .j  av a2s .c  om*/
 * @return Optional<Object>
 */
private static Optional<Object> jsonElementToObject(JsonElement element) {
    Object result = null;

    if (element.isJsonObject()) {
        result = dataViewFromJson(element.getAsJsonObject());
    } else if (element.isJsonPrimitive()) {
        JsonPrimitive prim = element.getAsJsonPrimitive();

        if (prim.isBoolean()) {
            result = prim.getAsBoolean();
        } else if (prim.isNumber()) {
            result = prim.getAsNumber().intValue();
        } else if (prim.isString()) {
            result = prim.getAsString();
        }
    } else if (element.isJsonArray()) {
        List<Object> list = new ArrayList<Object>();
        JsonArray arr = element.getAsJsonArray();
        arr.forEach(new Consumer<JsonElement>() {
            @Override
            public void accept(JsonElement t) {
                Optional<Object> translated = jsonElementToObject(t);
                if (translated.isPresent()) {
                    list.add(translated.get());
                }
            }
        });

        result = list;
    }

    return Optional.ofNullable(result);
}

From source file:com.hkm.disqus.api.gson.PostTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    // Return null if not a post object
    if (!type.getType().equals(Post.class)) {
        return null;
    }//from   w  ww  . j a  v a  2  s  .co  m

    // Get delegate
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    // Return adapter
    return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonElement jsonTree = gson.fromJson(in, JsonElement.class);
            JsonElement forum = jsonTree.getAsJsonObject().get("forum");
            JsonElement thread = jsonTree.getAsJsonObject().get("thread");

            // Process the post with the delegate
            T post = delegate.fromJsonTree(jsonTree);

            // Process forum and thread if needed
            if (forum.isJsonObject()) {
                ((Post) post).forum = gson.fromJson(forum, Forum.class);
            }
            if (thread.isJsonObject()) {
                ((Post) post).thread = gson.fromJson(thread, Thread.class);
            }

            // Return post
            return post;
        }

    };

}

From source file:com.hkm.disqus.api.gson.ThreadTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, TypeToken<T> type) {
    // Return null if not the thread type
    if (!type.getType().equals(Thread.class)) {
        return null;
    }/*from www  .  j a va 2  s  .  c o m*/

    // Get delegate
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    // Return adapter
    return new TypeAdapter<T>() {

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonElement jsonTree = gson.fromJson(in, JsonElement.class);
            JsonElement forum = jsonTree.getAsJsonObject().get("forum");
            JsonElement author = jsonTree.getAsJsonObject().get("author");
            JsonElement category = jsonTree.getAsJsonObject().get("category");

            // Process the thread with the delegate
            T thread = delegate.fromJsonTree(jsonTree);

            // Process forum and author if needed
            if (forum.isJsonObject()) {
                ((Thread) thread).forum = gson.fromJson(forum, Forum.class);
            }
            if (author.isJsonObject()) {
                ((Thread) thread).author = gson.fromJson(author, User.class);
            }
            if (category.isJsonObject()) {
                ((Thread) thread).category = gson.fromJson(category, Category.class);
            }

            // Return thread
            return thread;
        }

    };

}

From source file:com.hybris.datahub.service.impl.DefaultJsonService.java

License:Open Source License

@Override
public List<Map<String, String>> parse(final String json) {
    final List<Map<String, String>> result = new LinkedList<Map<String, String>>();
    final JsonElement jsonElement = new JsonParser().parse(json);
    if (jsonElement.isJsonArray()) {
        final Iterator<JsonElement> iterator = jsonElement.getAsJsonArray().iterator();
        while (iterator.hasNext()) {
            final JsonElement jsonElementInArray = iterator.next();
            result.add(convertJsonObject(jsonElementInArray.getAsJsonObject()));
        }/*from  ww w  .j ava2s .co  m*/
    } else if (jsonElement.isJsonObject()) {
        result.add(convertJsonObject(jsonElement.getAsJsonObject()));
    }
    return result;
}

From source file:com.ibasco.agql.core.AbstractWebApiInterface.java

License:Open Source License

/**
 * Converts the underlying processed content to a {@link com.google.gson.JsonObject} instance
 *//*w ww.  j a v a2s .  co  m*/
@SuppressWarnings("unchecked")
private <A> A postProcessConversion(Res response) {
    log.debug("ConvertToJson for Response = {}, {}", response.getMessage().getStatusCode(),
            response.getMessage().getHeaders());
    JsonElement processedElement = response.getProcessedContent();
    if (processedElement != null) {
        if (processedElement.isJsonObject())
            return (A) processedElement.getAsJsonObject();
        else if (processedElement.isJsonArray())
            return (A) processedElement.getAsJsonArray();
    }
    throw new AsyncGameLibUncheckedException("No parsed content found for response" + response);
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.adapters.SteamAssetClassInfoMapDeserializer.java

License:Open Source License

@Override
public Map<String, SteamAssetClassInfo> deserialize(JsonElement json, Type typeOfT,
        JsonDeserializationContext context) throws JsonParseException {
    Map<String, SteamAssetClassInfo> map = new HashMap<>();
    JsonObject jObject = json.getAsJsonObject();
    for (Map.Entry<String, JsonElement> entry : jObject.entrySet()) {
        String key = entry.getKey();
        JsonElement value = entry.getValue();
        //Only process entries that are of type object
        if (value.isJsonObject()) {
            map.put(key, context.deserialize(value, SteamAssetClassInfo.class));
        }/*from  ww w .jav  a2s.com*/
    }
    log.debug("Finished populating map. Total Map Size: {}", map.size());
    return map;
}

From source file:com.ibasco.agql.protocols.valve.steam.webapi.adapters.SteamAssetDescDeserializer.java

License:Open Source License

@Override
public SteamAssetDescription deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    SteamAssetDescription desc = new SteamAssetDescription();
    JsonObject jsonObj = json.getAsJsonObject();
    String type = jsonObj.getAsJsonPrimitive("type").getAsString();
    String value = jsonObj.getAsJsonPrimitive("value").getAsString();
    Map<String, String> mAppData = new HashMap<>();
    JsonElement appData = jsonObj.get("app_data");
    if (appData.isJsonObject()) {
        desc.setAppData(context.deserialize(appData, HashMap.class));
    } else {//from  w  w  w .ja v a2s . c o  m
        desc.setAppData(mAppData);
    }
    desc.setType(type);
    desc.setValue(value);
    return desc;
}