Example usage for com.google.gson JsonPrimitive getAsNumber

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

Introduction

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

Prototype

@Override
public Number getAsNumber() 

Source Link

Document

convenience method to get this element as a Number.

Usage

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  w w  w.j  a v a  2 s .co m*/
 * @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.ibm.streamsx.topology.generator.spl.SPLGenerator.java

License:Open Source License

/**
 * Append the value with the correct SPL suffix. Integer & Double do not
 * require a suffix// w  w w .jav  a 2  s . c  om
 */
static void numberLiteral(StringBuilder sb, JsonPrimitive value, String type) {
    String suffix = "";

    switch (type) {
    case "INT8":
        suffix = "b";
        break;
    case "INT16":
        suffix = "h";
        break;
    case "INT32":
        break;
    case "INT64":
        suffix = "l";
        break;

    case "UINT8":
        suffix = "ub";
        break;
    case "UINT16":
        suffix = "uh";
        break;
    case "UINT32":
        suffix = "uw";
        break;
    case "UINT64":
        suffix = "ul";
        break;

    case "FLOAT32":
        suffix = "w";
        break; // word, meaning 32 bits
    case "FLOAT64":
        break;
    }

    String literal;

    if (value.isNumber() && isUnsignedInt(type)) {
        Number nv = value.getAsNumber();

        if ("UINT64".equals(type))
            literal = Long.toUnsignedString(nv.longValue());
        else if ("UINT32".equals(type))
            literal = Integer.toUnsignedString(nv.intValue());
        else if ("UINT16".equals(type))
            literal = Integer.toUnsignedString(Short.toUnsignedInt(nv.shortValue()));
        else
            literal = Integer.toUnsignedString(Byte.toUnsignedInt(nv.byteValue()));
    } else {
        literal = value.getAsNumber().toString();
    }

    sb.append(literal);
    sb.append(suffix);
}

From source file:com.ikanow.infinit.e.data_model.store.MongoDbUtil.java

License:Apache License

public static Object encodeUnknown(JsonElement from) {
    if (from.isJsonArray()) { // Array
        return encodeArray(from.getAsJsonArray());
    } //TESTED//www  .  j  a  v  a 2 s.  co m
    else if (from.isJsonObject()) { // Object
        JsonObject obj = from.getAsJsonObject();
        // Check for OID/Date:
        if (1 == obj.entrySet().size()) {
            if (obj.has("$date")) {
                try {
                    return _format.parse(obj.get("$date").getAsString());
                } catch (ParseException e) {
                    try {
                        return _format2.parse(obj.get("$date").getAsString());
                    } catch (ParseException e2) {
                        return null;
                    }
                }
            } //TESTED
            else if (obj.has("$oid")) {
                return new ObjectId(obj.get("$oid").getAsString());
            } //TESTED                
        }
        return encode(obj);
    } //TESTED
    else if (from.isJsonPrimitive()) { // Primitive
        JsonPrimitive val = from.getAsJsonPrimitive();
        if (val.isNumber()) {
            return val.getAsNumber();
        } //TESTED
        else if (val.isBoolean()) {
            return val.getAsBoolean();
        } //TESTED
        else if (val.isString()) {
            return val.getAsString();
        } //TESTED
    } //TESTED
    return null;
}

From source file:com.jayway.jsonpath.internal.spi.json.GsonJsonProvider.java

License:Apache License

public static Object unwrap(Object o) {

    if (o == null) {
        return null;
    }//from w ww.  j a  va2 s  .c  o  m
    if (!(o instanceof JsonElement)) {
        return o;
    }

    JsonElement e = (JsonElement) o;

    if (e.isJsonNull()) {
        return null;
    } else if (e.isJsonPrimitive()) {

        JsonPrimitive p = e.getAsJsonPrimitive();
        if (p.isString()) {
            return p.getAsString();
        } else if (p.isBoolean()) {
            return p.getAsBoolean();
        } else if (p.isNumber()) {
            return unwrapNumber(p.getAsNumber());
        }
    }
    return o;
}

From source file:com.jayway.jsonpath.spi.json.GsonJsonProvider.java

License:Apache License

public Object unwrap(final Object o) {

    if (o == null) {
        return null;
    }/*from w  ww. j  a  v a  2 s  .  c  o  m*/

    if (!(o instanceof JsonElement)) {
        return o;
    }

    JsonElement e = (JsonElement) o;

    if (e.isJsonNull()) {
        return null;
    } else if (e.isJsonPrimitive()) {

        JsonPrimitive p = e.getAsJsonPrimitive();
        if (p.isString()) {
            return p.getAsString();
        } else if (p.isBoolean()) {
            return p.getAsBoolean();
        } else if (p.isNumber()) {
            return unwrapNumber(p.getAsNumber());
        }
    }

    return o;
}

From source file:com.kurento.kmf.jsonrpcconnector.JsonUtils.java

License:Open Source License

public Object toPrimitiveObject(JsonElement element) {

    JsonPrimitive primitive = (JsonPrimitive) element;
    if (primitive.isBoolean()) {
        return primitive.getAsBoolean();
    } else if (primitive.isNumber()) {
        Number number = primitive.getAsNumber();
        double value = number.doubleValue();
        if (((int) value == value)) {
            return (int) value;
        } else {/*from  www .  j  a v  a  2s .  c  o  m*/
            return (float) value;
        }
    } else if (primitive.isString()) {
        return primitive.getAsString();
    } else {
        throw new RuntimeException("Unrecognized JsonPrimitive: " + primitive);
    }
}

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   w  ww.j  av a2 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();
            }/*  w ww  .  j  a v a  2 s .  c o m*/
        } else {
            return n;
        }
    } else if (e.isBoolean()) {
        return e.getAsBoolean();
    } else {
        return e.getAsString();
    }
}

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 .  ja  v a2s  . 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}.
 * /* w  w  w  . j  a  v a  2  s. 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;

}