Example usage for com.google.gson JsonPrimitive getAsString

List of usage examples for com.google.gson JsonPrimitive getAsString

Introduction

In this page you can find the example usage for com.google.gson JsonPrimitive getAsString.

Prototype

@Override
public String getAsString() 

Source Link

Document

convenience method to get this element as a String.

Usage

From source file:com.bzcentre.dapiPush.MeetingPayload.java

License:Open Source License

private Object extractAps(JsonElement in) {
    if (in == null || in.isJsonNull())
        return null;

    if (in.isJsonArray()) {
        List<Object> list = new ArrayList<>();
        JsonArray arr = in.getAsJsonArray();
        for (JsonElement anArr : arr) {
            list.add(extractAps(anArr));
        }//from w w w  .  j  a  va 2 s . c om
        return list;
    } else if (in.isJsonObject()) {
        Map<String, Object> map = new LinkedTreeMap<>();
        JsonObject obj = in.getAsJsonObject();
        Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
        for (Map.Entry<String, JsonElement> entry : entitySet) {
            map.put(entry.getKey(), extractAps(entry.getValue()));
            NginxClojureRT.log.debug(TAG + entry.getKey() + "=>" + map.get(entry.getKey()) + "=>"
                    + map.get(entry.getKey()).getClass().getTypeName());
            switch (entry.getKey()) {
            case "dapi":
                this.setDapi(map.get(entry.getKey()));
                break;
            case "acme1":
                this.setAcme1(map.get(entry.getKey()));
                break;
            case "acme2":
                this.setAcme2(map.get(entry.getKey()));
                break;
            case "acme3":
                this.setAcme3(map.get(entry.getKey()));
                break;
            case "acme4":
                this.setAcme4(map.get(entry.getKey()));
                break;
            case "acme5":
                this.setAcme5(map.get(entry.getKey()));
                break;
            case "acme6":
                this.setAcme6(map.get(entry.getKey()));
                break;
            case "acme7":
                this.setAcme7(map.get(entry.getKey()));
                break;
            case "acme8":
                this.setAcme8(map.get(entry.getKey()));
                break;
            case "aps":
                NginxClojureRT.log.debug(TAG + "aps initialized");
                break;
            case "badge":
                this.getAps().setBadge(map.get(entry.getKey()));
                break;
            case "sound":
                this.getAps().setSound(map.get(entry.getKey()));
                break;
            case "alert":
                NginxClojureRT.log.debug(TAG + "alert initialized");
                break;
            case "title":
                this.getAps().getAlert().setTitle(map.get(entry.getKey()));
                break;
            case "body":
                this.getAps().getAlert().setBody(map.get(entry.getKey()));
                break;
            case "action-loc-key":
                this.getAps().getAlert().setActionLocKey(map.get(entry.getKey()));
                break;
            default:
                NginxClojureRT.log.info(TAG + "Unhandled field : " + entry.getKey());
                break;
            }
        }
        return map;
    } else if (in.isJsonPrimitive()) {
        JsonPrimitive prim = in.getAsJsonPrimitive();
        if (prim.isBoolean()) {
            return prim.getAsBoolean();
        } else if (prim.isString()) {
            return prim.getAsString();
        } else if (prim.isNumber()) {
            Number num = prim.getAsNumber();
            // here you can handle double int/long values
            // and return any type you want
            // this solution will transform 3.0 float to long values
            if (Math.ceil(num.doubleValue()) == num.longValue()) {
                return num.longValue();
            } else {
                return num.doubleValue();
            }
        }
    }
    NginxClojureRT.log.info("Handling json null");
    return null;
}

From source file:com.ca.dvs.utilities.lisamar.JDBCUtil.java

License:Open Source License

@SuppressWarnings("unchecked")
/**//from   w  ww  .  ja va2 s .c  o  m
 * Get the seed data of the specified entity set from Raml mode of OData Service
 * @param tagName - the name of entity set 
 * @return - the list of Map<String, Object>
 */
private List<Map<String, Object>> getSampleObjects(final String tagName) {

    /* Sample data:
      "/books": {                  "/<EntitySetName>"
        "schema": "books",            "<EntitySetName>"
        "example": {
    "size": 2,
    "books": [               "<EntitySetName>"
      {
        "id": 1,
        "name": "The Hobbit; or, There and Back Again",
        "isbn": "054792822X",
        "author_id": 1
      },
      {
        "id": 2,
        "name": "The Fellowship of the Ring",
        "isbn": "B007978NPG",
        "author_id": 1
      }
    ]
        }
      }         
    */

    Object dataObject = null;
    Object curObject = null;

    if (sampleData.size() == 0)
        return null;

    if (tagName == null || tagName.isEmpty())
        return null;

    curObject = sampleData.get("/" + tagName); //looking for /<EmtotySetName>
    if (curObject != null) {
        Map<String, Object> mapObjectList = null;
        mapObjectList = (Map<String, Object>) curObject;
        Object schemaObject = mapObjectList.get("schema");
        String schemaValue = schemaObject.toString();
        if (schemaObject instanceof JsonPrimitive) {
            JsonPrimitive sObject = (JsonPrimitive) schemaObject;
            schemaValue = sObject.getAsString();
        }
        if (schemaValue.equals(tagName)) {
            curObject = mapObjectList.get("example");
            if (curObject != null) {
                HashMap<String, Object> exampleObject = null;
                if (curObject instanceof JsonObject) {
                    JsonObject jsonObj = (JsonObject) curObject;
                    try {
                        exampleObject = convertJsonToMap(jsonObj.toString());
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        Map<String, Object> err = new LinkedHashMap<String, Object>();
                        err.put("entitySet", tagName);
                        err.put("record", jsonObj.toString());
                        err.put("warning", e.getMessage());
                        insertDataErrors.add(err);
                        return null;
                    }
                } else if (curObject instanceof LinkedHashMap) {
                    exampleObject = (HashMap<String, Object>) curObject;
                } else if (curObject instanceof HashMap) {
                    exampleObject = (HashMap<String, Object>) curObject;
                }

                if (exampleObject == null)
                    return null;

                dataObject = exampleObject.get(tagName);
            }
        }
    }

    // no sample data for the specified entity
    if (dataObject == null)
        return null;

    List<Map<String, Object>> samples = (List<Map<String, Object>>) dataObject;
    return samples;

}

From source file:com.ca.dvs.utilities.lisamar.JDBCUtil.java

License:Open Source License

@SuppressWarnings("unchecked")
/**//from w w  w . ja v a  2  s . c  o  m
 * Get the seed data of the specified entity set from Map<String, Object>
 * 
 * @param tagName   - entity set
 * @param map      - Map<String, Object>
 * @return         - the list of Map<String, Object>
 */
private List<Map<String, Object>> getSampleObjects(final String tagName, final Map<String, Object> map) {

    Map<String, Object> myMap = new HashMap<String, Object>();
    myMap = map;

    if (myMap.size() == 0)
        return null;

    if (tagName == null || tagName.isEmpty())
        return null;

    Object dataObject = myMap.get(tagName);
    if (dataObject == null)
        return null;

    List<Map<String, Object>> samples = new ArrayList<Map<String, Object>>();
    try {
        if (dataObject instanceof ArrayList) {
            samples = (List<Map<String, Object>>) dataObject;
        } else if (dataObject instanceof HashMap) {
            samples.add((Map<String, Object>) dataObject);
        } else if (dataObject instanceof LinkedHashMap) {
            samples.add((Map<String, Object>) dataObject);
        } else if (dataObject instanceof JsonObject) {
            samples.add((Map<String, Object>) convertJsonToMap(dataObject.toString()));
        } else if (dataObject instanceof JsonPrimitive) {
            JsonPrimitive jsonObject = (JsonPrimitive) dataObject;
            samples.add((Map<String, Object>) convertJsonToMap(jsonObject.getAsString()));
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return samples;

}

From source file:com.canoo.dolphin.impl.codec.OptimizedJsonCodec.java

License:Apache License

@Override
public List<Command> decode(String transmitted) {
    Assert.requireNonNull(transmitted, "transmitted");
    LOG.trace("Decoding message: {}", transmitted);
    try {// w ww  . ja  v a  2 s .  c  om
        final List<Command> commands = new ArrayList<>();
        final JsonArray array = (JsonArray) new JsonParser().parse(transmitted);

        for (final JsonElement jsonElement : array) {
            final JsonObject command = (JsonObject) jsonElement;
            JsonPrimitive idPrimitive = command.getAsJsonPrimitive("id");

            String id = null;
            if (idPrimitive != null) {
                id = idPrimitive.getAsString();
            }
            LOG.trace("Decoding command: {}", id);
            CommandEncoder<?> encoder = null;
            if (id != null) {
                encoder = DECODERS.get(id);
            }
            if (encoder != null) {
                commands.add(encoder.decode(command));
            } else {
                commands.addAll(fallBack.decode("[" + command.toString() + "]"));
            }
        }
        LOG.trace("Decoded command list with {} commands", commands.size());
        return commands;
    } catch (ClassCastException | NullPointerException ex) {
        throw new JsonParseException("Illegal JSON detected", ex);
    }
}

From source file:com.canoo.dolphin.impl.codec.ValueEncoder.java

License:Apache License

static Object decodeValue(JsonElement jsonElement) {
    if (jsonElement == null || jsonElement.isJsonNull()) {
        return null;
    }//from w w w . j a  v a2s .  c  o  m
    if (!jsonElement.isJsonPrimitive()) {
        throw new JsonParseException("Illegal JSON detected");
    }
    final JsonPrimitive value = (JsonPrimitive) jsonElement;

    if (value.isString()) {
        return value.getAsString();
    } else if (value.isBoolean()) {
        return value.getAsBoolean();
    } else if (value.isNumber()) {
        return value.getAsNumber();
    }
    throw new JsonParseException("Currently only String, Boolean, or Number are allowed as primitives");
}

From source file:com.cloudbase.CBNaturalDeserializer.java

License:Open Source License

private Object handlePrimitive(JsonPrimitive json) {
    if (json.isBoolean())
        return json.getAsBoolean();
    else if (json.isString())
        return json.getAsString();
    else {/*from  www  .  ja v a2s .com*/
        BigDecimal bigDec = json.getAsBigDecimal();
        // Find out if it is an int type
        try {
            bigDec.toBigIntegerExact();
            try {
                return bigDec.intValueExact();
            } catch (ArithmeticException e) {
            }
            return bigDec.longValue();
        } catch (ArithmeticException e) {
        }
        // Just return it as a double
        return bigDec.doubleValue();
    }
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

/**
 * Calculate the objecthash for a Gson JsonElement object, with a custom redaction prefix string.
 * @param o the Gson JsonElement to calculated the objecthash for.
 * @param r the string to use as a prefix to indicate that a string should be treated as a redacted subobject.
 * @return the objecthash for this object
 * @throws ContinusecException upon error
 *//*ww  w.j a  v  a2s  . c  om*/
public static final byte[] objectHashWithRedaction(JsonElement o, String r) throws ContinusecException {
    if (o == null || o.isJsonNull()) {
        return hashNull();
    } else if (o.isJsonArray()) {
        return hashArray(o.getAsJsonArray(), r);
    } else if (o.isJsonObject()) {
        return hashObject(o.getAsJsonObject(), r);
    } else if (o.isJsonPrimitive()) {
        JsonPrimitive p = o.getAsJsonPrimitive();
        if (p.isBoolean()) {
            return hashBoolean(p.getAsBoolean());
        } else if (p.isNumber()) {
            return hashDouble(p.getAsDouble());
        } else if (p.isString()) {
            return hashString(p.getAsString(), r);
        } else {
            throw new InvalidObjectException();
        }
    } else {
        throw new InvalidObjectException();
    }
}

From source file:com.continusec.client.ObjectHash.java

License:Apache License

private static final JsonElement shedObject(JsonObject o, String r) throws ContinusecException {
    JsonObject rv = new JsonObject();
    for (Map.Entry<String, JsonElement> e : o.entrySet()) {
        JsonElement v = e.getValue();/*from www  . j  a va  2 s. c o m*/
        if (v.isJsonArray()) {
            JsonArray a = v.getAsJsonArray();
            if (a.size() == 2) {
                rv.add(e.getKey(), shedRedactable(a.get(1), r));
            } else {
                throw new InvalidObjectException();
            }
        } else if (v.isJsonPrimitive()) {
            JsonPrimitive p = v.getAsJsonPrimitive();
            if (p.isString()) {
                if (p.getAsString().startsWith(r)) {
                    // all good, but we shed it.
                } else {
                    throw new InvalidObjectException();
                }
            } else {
                throw new InvalidObjectException();
            }
        } else {
            throw new InvalidObjectException();
        }
    }
    return rv;
}

From source file:com.continuuity.loom.macro.Expander.java

License:Apache License

/**
 * Given a JSON tree, find the element specified by the path (or the root if path is null). In that subtree,
 * recursively traverse all elements, and expand all String typed right hand side values.  If a macro cannot be
 * expanded due to the cluster object missing certain data, that macro will be left unexpanded.
 *
 * @param json A JSON tree//from ww  w .ja v  a  2s.  com
 * @param path the path to expand under
 * @param cluster the cluster to use for expanding macros.
 * @param nodes the cluster nodes to use for expanding macros.
 * @param node the cluster node to use for expanding macros.
 * @return a new JSON tree if any expansion took place, and the original JSON tree otherwise.
 * @throws SyntaxException if a macro expression is ill-formed.
 * @throws IncompleteClusterException if the cluster does not have the meta data to expand all macros.
 */
public static JsonElement expand(JsonElement json, @Nullable java.util.List<String> path, Cluster cluster,
        Set<Node> nodes, Node node) throws SyntaxException, IncompleteClusterException {

    // if path is given,
    if (path != null && !path.isEmpty()) {
        String first = path.get(0);
        if (json.isJsonObject()) {
            JsonObject object = json.getAsJsonObject();
            JsonElement json1 = object.get(first);
            if (json1 != null) {
                JsonElement expanded = expand(json1, path.subList(1, path.size()), cluster, nodes, node);
                if (expanded != json1) {
                    // only construct new json object if actual expansion happened
                    JsonObject object1 = new JsonObject();
                    for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
                        object1.add(entry.getKey(), entry.getKey().equals(first) ? expanded : entry.getValue());
                    }
                    return object1;
                }
            }
        }
        // path was given, but either no corresponding subtree was found or no expansion happened...
        return json;
    }

    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isString()) {
            String value = primitive.getAsString();
            String expanded = expand(value, cluster, nodes, node);
            if (!expanded.equals(value)) {
                // only return a new json element if actual expansion happened
                return new JsonPrimitive(expanded);
            }
        }
    }

    if (json.isJsonArray()) {
        JsonArray array = json.getAsJsonArray();
        JsonArray array1 = new JsonArray();
        boolean expansionHappened = false;
        for (JsonElement element : array) {
            JsonElement expanded = expand(element, path, cluster, nodes, node);
            if (expanded != element) {
                expansionHappened = true;
            }
            array1.add(expanded);
        }
        // only return a new json array if actual expansion happened
        if (expansionHappened) {
            return array1;
        }
    }

    if (json.isJsonObject()) {
        JsonObject object = json.getAsJsonObject();
        JsonObject object1 = new JsonObject();
        boolean expansionHappened = false;
        for (Map.Entry<String, JsonElement> entry : object.entrySet()) {
            JsonElement expanded = expand(entry.getValue(), path, cluster, nodes, node);
            if (expanded != entry.getValue()) {
                expansionHappened = true;
            }
            object1.add(entry.getKey(), expand(entry.getValue(), path, cluster, nodes, node));
        }
        if (expansionHappened) {
            return object1;
        }
    }

    return json;
}

From source file:com.couchbase.plugin.basement.api.Client.java

License:Open Source License

private void addJsonElement(String key, JsonElement value, HashMap<String, Object> map) {

    if (value.isJsonArray()) {
        JsonArray jsonArray = value.getAsJsonArray();

        ArrayList listAsValue = new ArrayList<HashMap<String, Object>>();

        HashMap<String, Object> listElementMap = new HashMap<String, Object>();

        Iterator<JsonElement> jsonArrayIterator = jsonArray.iterator();
        while (jsonArrayIterator.hasNext()) {
            JsonElement jsonElement = jsonArrayIterator.next();

            listAsValue.add(parse(jsonElement.toString()));

        }//from   ww w .  j  a va2s  .com

        map.put(key, listAsValue);

    } else if (value.isJsonPrimitive()) {
        // check the type using JsonPrimitive
        // TODO: check all types
        JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive();
        if (jsonPrimitive.isNumber()) {
            map.put(key, jsonPrimitive.getAsInt());
        } else {
            map.put(key, jsonPrimitive.getAsString());
        }
    } else {
        map.put(key, parse(value.toString()));
    }

}