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:io.webfolder.cdp.session.WSAdapter.java

License:Open Source License

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void onTextMessage(final WebSocket websocket, final String data) throws Exception {
    executor.execute(() -> {//  www. j  a va  2 s  .  c o m
        log.debug(data);
        JsonElement json = gson.fromJson(data, JsonElement.class);
        JsonObject object = json.getAsJsonObject();
        JsonElement idElement = object.get("id");
        if (idElement != null) {
            String id = idElement.getAsString();
            if (id != null) {
                int valId = (int) parseDouble(id);
                WSContext context = contextList.get(valId);
                if (context != null) {
                    JsonObject error = object.getAsJsonObject("error");
                    if (error != null) {
                        int code = (int) error.getAsJsonPrimitive("code").getAsDouble();
                        String message = error.getAsJsonPrimitive("message").getAsString();
                        context.setError(new CommandException(code, message));
                    } else {
                        context.setData(json);
                    }
                }
            }
        } else {
            JsonElement method = object.get("method");
            if (method != null && method.isJsonPrimitive()) {
                String eventName = method.getAsString();
                if ("Inspector.detached".equals(eventName) && session != null) {
                    if (session != null) {
                        Thread thread = new Thread(new TerminateSession(session, object));
                        thread.setName("cdp4j-terminate");
                        thread.setDaemon(true);
                        thread.start();
                        session = null;
                    }
                } else {
                    Events event = events.get(eventName);
                    if (event != null) {
                        JsonElement params = object.get("params");
                        Object value = gson.fromJson(params, event.klass);
                        for (EventListener next : eventListeners) {
                            executor.execute(() -> {
                                next.onEvent(event, value);
                            });
                        }
                    }
                }
            }
        }
    });
}

From source file:it.geosolutions.android.map.geostore.model.GeoStoreTypeAdapter.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   ww w .  j  ava 2s.c om
public List<T> deserialize(JsonElement json, java.lang.reflect.Type typeOfT, JsonDeserializationContext ctx)
        throws JsonParseException {
    List<T> vals = new ArrayList<T>();

    if (json.isJsonArray()) {
        for (JsonElement e : json.getAsJsonArray()) {
            vals.add((T) ctx.deserialize(e, this.type));
        }
    } else if (json.isJsonObject()) {
        vals.add((T) ctx.deserialize(json, type));
    } else if (json.isJsonPrimitive()) {
        //empty is a string
        return vals;
    } else {
        throw new RuntimeException("Unexpected JSON type: " + json.getClass());
    }
    return vals;
}

From source file:it.infn.mw.iam.core.util.PoliteJsonMessageSource.java

License:Apache License

/**
 * Get a value from a single map @param code @param locale @param lang @return
 *//*from ww w.  j  a v  a2  s .  com*/
private String getValue(String code, JsonObject lang) {

    // if there's no language map, nothing to look up
    if (lang == null) {
        return null;
    }

    JsonElement e = lang;

    Iterable<String> parts = Splitter.on('.').split(code);
    Iterator<String> it = parts.iterator();

    String value = null;

    while (it.hasNext()) {
        String p = it.next();
        if (e.isJsonObject()) {
            JsonObject o = e.getAsJsonObject();
            if (o.has(p)) {
                e = o.get(p); // found the next level
                if (!it.hasNext()) {
                    // we've reached a leaf, grab it
                    if (e.isJsonPrimitive()) {
                        value = e.getAsString();
                    }
                }
            } else {
                // didn't find it, stop processing
                break;
            }
        } else {
            // didn't find it, stop processing
            break;
        }
    }

    return value;

}

From source file:it.reply.orchestrator.dto.security.IndigoUserInfo.java

License:Apache License

/**
 * Create a {@link UserInfo} from its JSON representation.
 * /*  w  w w  .jav  a  2s.co  m*/
 * @param obj
 *          {@link JsonObject} containing the JSON representation.
 * @return the UserInfo.
 */
public static UserInfo fromJson(JsonObject obj) {
    IndigoUserInfo result = new IndigoUserInfo(DefaultUserInfo.fromJson(obj));
    if (obj.has(GROUPS_KEY) && obj.get(GROUPS_KEY).isJsonArray()) {
        List<String> groups = Lists.newArrayList();
        JsonArray groupsJson = obj.getAsJsonArray(GROUPS_KEY);
        for (JsonElement groupJson : groupsJson) {
            if (groupJson != null && groupJson.isJsonPrimitive()) {
                groups.add(groupJson.getAsString());
            }
        }
        result.setGroups(groups);
    }
    result.setOrganizationName(
            obj.has(ORGANIZATION_NAME_KEY) && obj.get(ORGANIZATION_NAME_KEY).isJsonPrimitive()
                    ? obj.get(ORGANIZATION_NAME_KEY).getAsString()
                    : null);
    return result;
}

From source file:it.unibo.arces.wot.sepa.pattern.JSAP.java

License:Open Source License

private JsonObject merge(JsonObject temp, JsonObject jsap, boolean replace) {
    for (Entry<String, JsonElement> entry : temp.entrySet()) {
        JsonElement value = entry.getValue();
        String key = entry.getKey();

        if (!jsap.has(key)) {
            jsap.add(key, value);/*from w  ww. ja v  a 2 s.c  om*/
            continue;
        }

        if (value.isJsonPrimitive()) {
            if (!replace)
                continue;
            jsap.add(key, value);
        } else if (value.isJsonObject()) {
            JsonObject obj = merge(value.getAsJsonObject(), jsap.getAsJsonObject(key), replace);
            jsap.add(key, obj);
        } else if (value.isJsonArray()) {
            for (JsonElement arr : value.getAsJsonArray()) {
                jsap.getAsJsonArray(key).add(arr);
            }
        }
    }

    return jsap;
}

From source file:jk_5.nailed.api.chat.serialization.ComponentSerializer.java

License:Open Source License

@Nonnull
@Override/* ww w  .  j  a  v a 2 s  .c om*/
public BaseComponent deserialize(@Nonnull JsonElement json, @Nonnull Type typeOfT,
        @Nonnull JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonPrimitive()) {
        return new TextComponent(json.getAsString());
    }
    JsonObject object = json.getAsJsonObject();
    if (object.has("translate")) {
        return context.deserialize(json, TranslatableComponent.class);
    }
    return context.deserialize(json, TextComponent.class);
}

From source file:jp.pay.model.EventDataDeserializer.java

License:Open Source License

private Object deserializeJsonElement(JsonElement element) {
    if (element.isJsonNull()) {
        return null;
    } else if (element.isJsonObject()) {
        Map<String, Object> valueMap = new HashMap<String, Object>();
        populateMapFromJSONObject(valueMap, element.getAsJsonObject());
        return valueMap;
    } else if (element.isJsonPrimitive()) {
        return deserializeJsonPrimitive(element.getAsJsonPrimitive());
    } else if (element.isJsonArray()) {
        return deserializeJsonArray(element.getAsJsonArray());
    } else {//from   w w w .j ava 2s. c o  m
        System.err.println("Unknown JSON element type for element " + element + ". "
                + "If you're seeing this messaage, it's probably a bug in the Payjp Java "
                + "library. Please contact us by email at support@pay.jp.");
        return null;
    }
}

From source file:jp.yokomark.utils.gson.utils.JsonElementUtils.java

License:Open Source License

public static JsonPrimitive getAsJsonPrimitiveOrThrow(JsonElement element) throws JsonParseException {
    if (!element.isJsonPrimitive()) {
        throw new JsonParseException("this element is not a json primitive: " + element);
    }/*from   ww w.  ja  v a  2s. co  m*/
    return element.getAsJsonPrimitive();
}

From source file:jsondiscoverer.JsonSimpleDiscoverer.java

License:Open Source License

/**
 * Maps JSON types into ECORE types/*www  .j  a va2s.com*/
 * 
 * @param id Identifier of the feature (to infer the name of the type if non-primitive)
 * @param value {@link JsonElement} including the value
 * @return The mapped type (as {@link EClassifier}
 */
private EClassifier mapType(String id, JsonElement value) {
    if (id == null)
        throw new IllegalArgumentException("id cannot be null");
    if (value == null)
        throw new IllegalArgumentException("jsonObject cannot be null");

    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:JsonParser.ParseJson.java

public static void dumpJSONElement(JsonElement element, String type) {
    if (element.isJsonObject()) {
        //System.out.println("Is an object");
        JsonObject obj = element.getAsJsonObject();
        java.util.Set<java.util.Map.Entry<String, JsonElement>> entries = obj.entrySet();
        java.util.Iterator<java.util.Map.Entry<String, JsonElement>> iter = entries.iterator();
        while (iter.hasNext()) {
            java.util.Map.Entry<String, JsonElement> entry = iter.next();
            //  System.out.println("Key: " + entry.getKey());
            if (entry.getKey().toString().equals("instances")) {
                System.out.println("............Topic: ");
                dumpJSONElement(entry.getValue(), "topic");

            }//from  w ww  . j av  a2  s .  c  om
            if (entry.getKey().toString().equals("aspects")) {
                System.out.println("............aspects: ");
                dumpJSONElement(entry.getValue(), "aspect");

            } else if (entry.getKey().toString().equals("positives")) {
                System.out.println(".............Positive Words ");
                dumpJSONElement(entry.getValue(), "positive");
            } else if (entry.getKey().toString().equals("negatives")) {
                System.out.println(".............negatives Words ");
                dumpJSONElement(entry.getValue(), "negative");
            } else {
                dumpJSONElement(entry.getValue(), "");
            }

        }

    } else if (element.isJsonArray()) {
        JsonArray array = element.getAsJsonArray();
        //System.out.println("Is an array. Number of values: " + array.size());
        java.util.Iterator<JsonElement> iter = array.iterator();
        while (iter.hasNext()) {
            JsonElement entry = iter.next();

            dumpJSONElement(entry, "");
        }
    } else if (element.isJsonPrimitive()) {
        //System.out.println("Is a primitive");
        JsonPrimitive value = element.getAsJsonPrimitive();
        if (value.isBoolean()) {
            //System.out.println("Is boolean: " + value.getAsBoolean());
        } else if (value.isNumber()) {
            //  System.out.println("Is number: " + value.getAsNumber());
        } else if (value.isString()) {
            //if(!value.getAsString().equals("empty"))
            //{
            //if(type.equals("topic"))
            //{
            System.out.println(type + " :" + value.getAsString());
            //}
        }
    } else if (element.isJsonNull()) {
        System.out.println("Is NULL");
    } else {
        System.out.println("Error. Unknown type of element");
    }
}