Example usage for com.google.gson JsonPrimitive getAsBoolean

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

Introduction

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

Prototype

@Override
public boolean getAsBoolean() 

Source Link

Document

convenience method to get this element as a boolean value.

Usage

From source file:com.talvish.tales.auth.jwt.TokenManager.java

License:Apache License

/**
 * Helper method that takes a string segment (e.g. headers, claims) and 
 * base64 decodes, parses out the json and generates a map of the values. 
 * @param theSegment the segment to process
 * @return the map of values generated from the segment
 *//*from ww w. j a v a 2  s  . co m*/
private Map<String, Object> processSegment(String theSegment, int theSegmentIndex) {
    Map<String, Object> outputItems = new HashMap<>();
    ClaimDetails claimDetails;
    String claimName = null;
    JsonElement claimValue = null;

    try {
        JsonObject inputJson = (JsonObject) jsonParser
                .parse(new String(base64Decoder.decode(theSegment), utf8));
        for (Entry<String, JsonElement> entry : inputJson.entrySet()) {
            claimName = entry.getKey();
            claimValue = entry.getValue();
            claimDetails = this.claimHandlers.get(claimName);
            if (claimDetails != null) {
                outputItems.put(claimName,
                        claimDetails.getTypeAdapter().getFromFormatTranslator().translate(claimValue));
            } else if (claimValue.isJsonPrimitive()) {
                JsonPrimitive primitiveJson = (JsonPrimitive) claimValue;
                if (primitiveJson.isString()) {
                    outputItems.put(claimName, primitiveJson.getAsString());
                } else if (primitiveJson.isNumber()) {
                    outputItems.put(claimName, primitiveJson.getAsNumber());
                } else if (primitiveJson.isBoolean()) {
                    outputItems.put(claimName, primitiveJson.getAsBoolean());
                } else {
                    throw new IllegalArgumentException(String.format(
                            "Claim '%s' is a primitive json type with value '%s', which has no mechanism for translation.",
                            claimName, claimValue.getAsString()));
                }
            } else {
                throw new IllegalArgumentException(String.format(
                        "Claim '%s' is not a primitive json type with value '%s', which has no mechanism for translation.",
                        claimName, claimValue.getAsString()));
            }
        }
    } catch (JsonParseException e) {
        throw new IllegalArgumentException(
                String.format("Segment '%d' contains invalid json.", theSegmentIndex), e);
    } catch (TranslationException e) {
        // claim name will be set if we have this exception, if not it will be null and will not cause a problem
        // but to be safe for the value, which should also be not null, we check so no exceptions are thrown
        if (claimValue != null) {
            throw new IllegalArgumentException(
                    String.format("Claim '%s' in segment '%d' contains invalid data '%s'.", claimName,
                            theSegmentIndex, claimValue.getAsString()),
                    e);
        } else {
            throw new IllegalArgumentException(String.format(
                    "Claim '%s' in segment '%d' contains invalid data.", claimName, theSegmentIndex), e);
        }
    }
    return outputItems;
}

From source file:com.tsc9526.monalisa.tools.json.MelpJson.java

License:Open Source License

public static Object primitive(JsonPrimitive e) {
    if (e.isNumber()) {
        Number n = e.getAsNumber();
        if (n instanceof LazilyParsedNumber) {
            LazilyParsedNumber ln = (LazilyParsedNumber) n;
            String value = ln.toString();
            if (value.indexOf('.') >= 0) {
                return ln.doubleValue();
            } else {
                return ln.longValue();
            }/*from ww w .j a  v a2  s .  com*/
        } else {
            return n;
        }
    } else if (e.isBoolean()) {
        return e.getAsBoolean();
    } else {
        return e.getAsString();
    }
}

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  w  w  w.j  a v a  2s.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}./*from  www  . j a  v a2 s  .  co  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.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  ww .j a  va2 s . com*/
 * @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 {//  w  w  w .j a  v a 2  s .co 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.yandex.money.api.typeadapters.JsonUtils.java

License:Open Source License

/**
 * Gets nullable Boolean from a JSON object.
 *
 * @param object json object/* w  w  w.ja  va2 s . co m*/
 * @param memberName member's name
 * @return {@link Boolean} value
 */
public static Boolean getBoolean(JsonObject object, String memberName) {
    JsonPrimitive primitive = getPrimitiveChecked(object, memberName);
    return primitive == null ? null : primitive.getAsBoolean();
}

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 w  w  . j av  a  2 s  . c  o m*/
 * @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 a  va  2 s .c  o  m
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:de.azapps.mirakel.model.task.TaskDeserializer.java

License:Open Source License

private static void handleAdditionalEntries(final Task t, final String key, final JsonElement val) {
    if (val.isJsonPrimitive()) {
        final JsonPrimitive p = (JsonPrimitive) val;
        if (p.isBoolean()) {
            t.addAdditionalEntry(key, String.valueOf(val.getAsBoolean()));
        } else if (p.isNumber()) {
            t.addAdditionalEntry(key, String.valueOf(val.getAsInt()));
        } else if (p.isJsonNull()) {
            t.addAdditionalEntry(key, "null");
        } else if (p.isString()) {
            t.addAdditionalEntry(key, '"' + val.getAsString() + '"');
        } else {/* w w w. j av a 2  s  .  c om*/
            Log.w(TAG, "unknown json-type");
        }
    } else if (val.isJsonArray()) {
        final JsonArray a = (JsonArray) val;
        StringBuilder s = new StringBuilder("[");
        boolean first = true;
        for (final JsonElement e : a) {
            if (e.isJsonPrimitive()) {
                final JsonPrimitive p = (JsonPrimitive) e;
                final String add;
                if (p.isBoolean()) {
                    add = String.valueOf(p.getAsBoolean());
                } else if (p.isNumber()) {
                    add = String.valueOf(p.getAsInt());
                } else if (p.isString()) {
                    add = '"' + p.getAsString() + '"';
                } else if (p.isJsonNull()) {
                    add = "null";
                } else {
                    Log.w(TAG, "unknown json-type");
                    break;
                }
                s.append(first ? "" : ",").append(add);
                first = false;
            } else {
                Log.w(TAG, "unknown json-type");
            }
        }
        t.addAdditionalEntry(key, s + "]");
    } else {
        Log.w(TAG, "unknown json-type");
    }
}