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.vmware.xenon.common.serialization.ObjectCollectionTypeConverter.java

License:Open Source License

@Override
public Collection<Object> deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {

    if (!json.isJsonArray()) {
        throw new JsonParseException("Expecting a json array object but found: " + json);
    }/*from   ww w  .  j av a 2  s.  c o  m*/

    Collection<Object> result;
    if (TYPE_SET.equals(type)) {
        result = new HashSet<>();
    } else if (TYPE_LIST.equals(type) || TYPE_COLLECTION.equals(type)) {
        result = new LinkedList<>();
    } else {
        throw new JsonParseException("Unexpected target type: " + type);
    }

    JsonArray jsonArray = json.getAsJsonArray();
    for (JsonElement entry : jsonArray) {
        if (entry.isJsonNull()) {
            result.add(null);
        } else if (entry.isJsonPrimitive()) {
            JsonPrimitive elem = entry.getAsJsonPrimitive();
            Object value = null;
            if (elem.isBoolean()) {
                value = elem.getAsBoolean();
            } else if (elem.isString()) {
                value = elem.getAsString();
            } else if (elem.isNumber()) {
                // We don't know if this is an integer, long, float or double...
                BigDecimal num = elem.getAsBigDecimal();
                try {
                    value = num.longValueExact();
                } catch (ArithmeticException e) {
                    value = num.doubleValue();
                }
            } else {
                throw new RuntimeException("Unexpected value type for json element:" + elem);
            }
            result.add(value);
        } else {
            // keep JsonElement to prevent stringified json issues
            result.add(entry);
        }
    }
    return result;
}

From source file:com.voxelplugineering.voxelsniper.service.persistence.JsonDataSource.java

License:Open Source License

/**
 * Recursively converts the given {@link JsonElement} to a
 * {@link DataContainer}.// w  ww .j av  a 2  s. c  om
 * 
 * @param rootelement The element to convert
 * @return The new {@link DataContainer}
 */
public DataContainer toContainer(JsonElement rootelement) {
    DataContainer container = new MemoryContainer("");

    if (rootelement.isJsonObject()) {
        JsonObject root = rootelement.getAsJsonObject();
        for (Entry<String, JsonElement> entry : root.entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();
            if (element.isJsonPrimitive()) {
                JsonPrimitive primitive = element.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    container.writeBoolean(key, primitive.getAsBoolean());
                } else if (primitive.isString()) {
                    container.writeString(key, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    container.writeNumber(key, primitive.getAsNumber());
                }
            } else if (element.isJsonObject()) {
                container.writeContainer(key, toContainer(element));
            }
        }
    }

    return container;

}

From source file:com.voxelplugineering.voxelsniper.service.persistence.JsonDataSourceReader.java

License:Open Source License

/**
 * Recursively converts the given {@link JsonElement} to a {@link DataContainer}.
 * //from  w  w  w.  j av a2s .c  o  m
 * @param rootelement The element to convert
 * @return The new {@link DataContainer}
 */
public DataContainer toContainer(JsonElement rootelement) {
    DataContainer container = new MemoryContainer("");

    if (rootelement.isJsonObject()) {
        JsonObject root = rootelement.getAsJsonObject();
        for (Entry<String, JsonElement> entry : root.entrySet()) {
            String key = entry.getKey();
            JsonElement element = entry.getValue();
            if (element.isJsonPrimitive()) {
                JsonPrimitive primitive = element.getAsJsonPrimitive();
                if (primitive.isBoolean()) {
                    container.setBoolean(key, primitive.getAsBoolean());
                } else if (primitive.isString()) {
                    container.setString(key, primitive.getAsString());
                } else if (primitive.isNumber()) {
                    container.setNumber(key, primitive.getAsNumber());
                }
            } else if (element.isJsonObject()) {
                container.setContainer(key, toContainer(element));
            }
        }
    }

    return container;

}

From source file:com.vsthost.rnd.jpsolver.data.ValueBuilder.java

License:Apache License

public static Value fromJsonElement(JsonElement element) {
    // Check primitive types:
    if (element instanceof JsonNull) {
        // Return the NONE value:
        return Value.NONE;
    } else if (element instanceof JsonPrimitive) {
        // Cast and get the primitive:
        JsonPrimitive primitive = (JsonPrimitive) element;

        // Check primitive types:
        if (primitive.isBoolean()) {
            return primitive.getAsBoolean() ? BooleanValue.TRUE : BooleanValue.FALSE;
        } else if (primitive.isNumber()) {
            return new NumericValue(primitive.getAsBigDecimal());
        } else {/*from   w w  w. j  av  a  2 s.c  o m*/
            return new TextValue(primitive.getAsString());
        }
    } else if (element instanceof JsonArray) {
        // Cast and get the array:
        JsonArray array = (JsonArray) element;

        // Iterate over the elements and populate the return value:
        ValueList<Value> retval = new ValueList<Value>();
        for (JsonElement e : array) {
            retval.add(ValueBuilder.fromJsonElement(e));
        }

        // Done, return:
        return retval;
    } else {
        // Cast and get the object:
        JsonObject object = (JsonObject) element;

        // Iterate over the elements and populate the return value:
        ValueMap retval = new ValueMap();
        for (Map.Entry<String, JsonElement> e : object.entrySet()) {
            retval.put(e.getKey(), ValueBuilder.fromJsonElement(e.getValue()));
        }

        // Done, return:
        return retval;
    }
}

From source file:com.wso2telco.MePinStatusRequest.java

License:Open Source License

public String call() {
    String allowStatus = null;//from w  w  w  . j a  v  a2 s. c o  m

    String clientId = FileUtil.getApplicationProperty("mepin.clientid");
    String url = FileUtil.getApplicationProperty("mepin.url");
    url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId + "";
    log.info("MePIN Status URL: " + url);

    String authHeader = "Basic " + FileUtil.getApplicationProperty("mepin.accesstoken");

    try {
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();

        connection.setRequestMethod("GET");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", authHeader);

        String resp = "";
        int statusCode = connection.getResponseCode();
        InputStream is;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
        } else {
            is = connection.getErrorStream();
        }

        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String output;
        while ((output = br.readLine()) != null) {
            resp += output;
        }
        br.close();

        log.info("MePIN Status Response Code: " + statusCode + " " + connection.getResponseMessage());
        log.info("MePIN Status Response: " + resp);

        JsonObject responseJson = new JsonParser().parse(resp).getAsJsonObject();
        String respTransactionId = responseJson.getAsJsonPrimitive("transaction_id").getAsString();
        JsonPrimitive allowObject = responseJson.getAsJsonPrimitive("allow");

        if (allowObject != null) {
            allowStatus = allowObject.getAsString();
            if (Boolean.parseBoolean(allowStatus)) {
                allowStatus = "APPROVED";
                String sessionID = DatabaseUtils.getMePinSessionID(respTransactionId);
                DatabaseUtils.updateStatus(sessionID, allowStatus);
            }
        }

    } catch (IOException e) {
        log.error("Error while MePIN Status request" + e);
    } catch (SQLException e) {
        log.error("Error in connecting to DB" + e);
    }
    return allowStatus;
}

From source file:com.yahoo.yqlplus.example.apis.GeoSource.java

@Query
public Place getPlace(@Key("text") String text)
        throws InterruptedException, ExecutionException, TimeoutException {
    JsonObject jsonObject = HttpUtil.getJsonResponse(BASE_URL, "q",
            "select * from geo.places where text='" + text + "'");
    JsonPrimitive jsonObj = jsonObject.getAsJsonObject("query").getAsJsonObject("results")
            .getAsJsonObject("place").getAsJsonPrimitive("woeid");
    return new Place(text, jsonObj.getAsString());
}

From source file:com.yandex.money.api.typeadapters.JsonUtils.java

License:Open Source License

/**
 * Gets nullable String from a JSON object.
 *
 * @param object json object//  ww w  .j  a  va  2 s.c  o  m
 * @param memberName member's name
 * @return {@link String} value
 */
public static String getString(JsonObject object, String memberName) {
    JsonPrimitive primitive = getPrimitiveChecked(object, memberName);
    return primitive == null ? null : primitive.getAsString();
}

From source file:cosmos.records.JsonRecords.java

License:Apache License

/**
 * Parses a {@link JsonObject{ into a MapRecord. A duplicate key in the JsonObject will
 * overwrite the previous key.//from   w ww .  j ava2s.c om
 * @param map The JsonObject being parsed
 * @param generator Construct to generate a docId for this {@link MapRecord}
 * @return A MapRecord built from the {@link JsonObject}
 */
protected static MapRecord asMapRecord(JsonObject map, DocIdGenerator generator) {
    Map<Column, RecordValue<?>> data = Maps.newHashMap();
    for (Entry<String, JsonElement> entry : map.entrySet()) {
        final Column key = Column.create(entry.getKey());
        final JsonElement value = entry.getValue();

        if (value.isJsonNull()) {
            data.put(key, null);
        } else if (value.isJsonPrimitive()) {
            JsonPrimitive primitive = (JsonPrimitive) value;

            // Numbers
            if (primitive.isNumber()) {
                NumberRecordValue<?> v;

                double d = primitive.getAsDouble();
                if ((int) d == d) {
                    v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS);
                } else if ((long) d == d) {
                    v = new LongRecordValue((long) d, Defaults.EMPTY_VIS);
                } else {
                    v = new DoubleRecordValue(d, Defaults.EMPTY_VIS);
                }

                data.put(key, v);

            } else if (primitive.isString()) {
                // String
                data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS));

            } else if (primitive.isBoolean()) {
                // Boolean
                data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS));

            } else if (primitive.isJsonNull()) {
                // Is this redundant?
                data.put(key, null);
            } else {
                throw new RuntimeException("Unhandled primitive: " + primitive);
            }
        } else {
            throw new RuntimeException("Expected a String, Number or Boolean");
        }
    }

    return new MapRecord(data, generator.getDocId(data), Defaults.EMPTY_VIS);
}

From source file:cosmos.records.JsonRecords.java

License:Apache License

/**
 * Builds a {@link MultimapRecord} from the provided {@link JsonObject} using a docid
 * from the {@link DocIdGenerator}. This method will support lists of values for a key
 * in the {@link JsonObject} but will fail on values which are {@link JsonObject}s and 
 * values which have nested {@link JsonArray}s. 
 * @param map The {@link JsonObject} to build this {@link MultimapRecord} from
 * @param generator {@link DocIdGenerator} to construct a docid for this {@link MultimapRecord}
 * @return A {@link MultimapRecord} built from the provided arguments.
 */// w w  w  . j av  a2s .  c om
protected static MultimapRecord asMultimapRecord(JsonObject map, DocIdGenerator generator) {
    Multimap<Column, RecordValue<?>> data = HashMultimap.create();
    for (Entry<String, JsonElement> entry : map.entrySet()) {
        final Column key = Column.create(entry.getKey());
        final JsonElement value = entry.getValue();

        if (value.isJsonNull()) {
            data.put(key, null);
        } else if (value.isJsonPrimitive()) {
            JsonPrimitive primitive = (JsonPrimitive) value;

            // Numbers
            if (primitive.isNumber()) {
                NumberRecordValue<?> v;

                double d = primitive.getAsDouble();
                if ((int) d == d) {
                    v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS);
                } else if ((long) d == d) {
                    v = new LongRecordValue((long) d, Defaults.EMPTY_VIS);
                } else {
                    v = new DoubleRecordValue(d, Defaults.EMPTY_VIS);
                }

                data.put(key, v);

            } else if (primitive.isString()) {
                // String
                data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS));

            } else if (primitive.isBoolean()) {
                // Boolean
                data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS));

            } else if (primitive.isJsonNull()) {
                // Is this redundant?
                data.put(key, null);
            } else {
                throw new RuntimeException("Unhandled primitive: " + primitive);
            }
        } else if (value.isJsonArray()) {

            // Multimaps should handle the multiple values, not fail
            JsonArray values = value.getAsJsonArray();
            for (JsonElement element : values) {
                if (element.isJsonNull()) {
                    data.put(key, null);
                } else if (element.isJsonPrimitive()) {

                    JsonPrimitive primitive = (JsonPrimitive) element;

                    // Numbers
                    if (primitive.isNumber()) {
                        NumberRecordValue<?> v;

                        double d = primitive.getAsDouble();
                        if ((int) d == d) {
                            v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS);
                        } else if ((long) d == d) {
                            v = new LongRecordValue((long) d, Defaults.EMPTY_VIS);
                        } else {
                            v = new DoubleRecordValue(d, Defaults.EMPTY_VIS);
                        }

                        data.put(key, v);

                    } else if (primitive.isString()) {
                        // String
                        data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS));

                    } else if (primitive.isBoolean()) {
                        // Boolean
                        data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS));

                    } else if (primitive.isJsonNull()) {
                        // Is this redundant?
                        data.put(key, null);
                    } else {
                        throw new RuntimeException("Unhandled Json primitive: " + primitive);
                    }
                } else {
                    throw new RuntimeException("Expected a Json primitive");
                }
            }

        } else {
            throw new RuntimeException("Expected a String, Number or Boolean");
        }
    }

    return new MultimapRecord(data, generator.getDocId(data), Defaults.EMPTY_VIS);

}

From source file:Days.Day12.java

public int parseObject(JsonObject object) {
    boolean hasRed = false;
    int totaal = 0;
    for (Entry<String, JsonElement> entry : object.entrySet()) {
        if (entry.getKey().equalsIgnoreCase("red")) {
            hasRed = true;/*from  w  ww. j a  v  a 2  s  . co  m*/
            break;
        } else {
            try {
                totaal += Integer.parseInt(entry.getKey());
            } catch (NumberFormatException e) {

            }
        }
        if (entry.getValue().isJsonPrimitive()) {
            JsonPrimitive value = entry.getValue().getAsJsonPrimitive();
            if (value.isString() && value.getAsString().equalsIgnoreCase("red")) {
                hasRed = true;
                break;
            }
        }
    }
    if (!hasRed) {
        for (Entry<String, JsonElement> entry : object.entrySet()) {
            totaal += parseElement(entry.getValue());
        }
    }
    return totaal;
}