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.softwaremagico.tm.json.InterfaceAdapter.java

License:Open Source License

@Override
public T deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext)
        throws JsonParseException {

    JsonObject jsonObject = jsonElement.getAsJsonObject();
    JsonPrimitive prim = (JsonPrimitive) jsonObject.get(JSON_CLASSNAME);
    if (prim == null) {
        return null;
    }//from ww w . ja  va  2  s . c  om
    String className = prim.getAsString();
    return jsonDeserializationContext.deserialize(jsonObject.get(JSON_DATA), getObjectClass(className));
}

From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java

License:Open Source License

private @CheckForNull Object toSimpleJavaType(JsonElement jsonValue) {
    if (jsonValue == null)
        return null; //VR
    Object value = null;/*from w  w w .  ja  v  a  2  s.co m*/
    if (!jsonValue.isJsonNull()) {
        if (jsonValue.isJsonPrimitive()) {
            JsonPrimitive primitive = jsonValue.getAsJsonPrimitive();
            if (primitive.isBoolean()) {
                value = Boolean.valueOf(primitive.getAsBoolean());
            } else if (primitive.isNumber()) {
                value = Double.valueOf(primitive.getAsDouble());
            } else if (primitive.isString()) {
                value = primitive.getAsString();
            } else {
                throw UnexpectedException.forUnexpectedCodeBranchExecuted();
            }
        } else if (jsonValue.isJsonArray()) {
            //This simply does not work (?) 
            JsonArray array = jsonValue.getAsJsonArray();
            Object[] result = new Object[array.size()];
            for (int i = 0; i < array.size(); i++) {
                result[i] = toSimpleJavaType(array.get(i));
            }
            value = result;
        } else if (jsonValue.isJsonObject()) {
            //This simply does not work (?)
            //value = getGson().fromJson(jsonValue, Map.class );

            JsonObject obj = jsonValue.getAsJsonObject();
            Iterator<Entry<String, JsonElement>> properties = obj.entrySet().iterator();
            Map<String, Object> result = new HashMap<String, Object>();
            while (properties.hasNext()) {
                Entry<String, JsonElement> property = properties.next();
                JsonElement propertyValue = property.getValue();
                result.put(property.getKey(), toSimpleJavaType(propertyValue));
            }
            value = result;
        } else {
            throw UnexpectedException.forUnexpectedCodeBranchExecuted();
        }
    }

    return value;
}

From source file:com.stackmob.sdk.push.StackMobPushTokenDeserializer.java

License:Apache License

public StackMobPushToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    JsonObject obj = json.getAsJsonObject();

    JsonPrimitive tokenStringPrimitive = obj.getAsJsonPrimitive("token");
    String tokenString = tokenStringPrimitive.getAsString();

    JsonPrimitive tokenTypePrimitive = obj.getAsJsonPrimitive("type");
    StackMobPushToken.TokenType tokenType = StackMobPushToken.TokenType
            .valueOf(tokenTypePrimitive.getAsString());

    JsonPrimitive registeredMSPrimitive = obj.getAsJsonPrimitive("registered_milliseconds");
    long registeredMS = registeredMSPrimitive.getAsInt();

    return new StackMobPushToken(tokenString, tokenType, registeredMS);
}

From source file:com.synflow.cx.internal.instantiation.properties.Specializer.java

License:Open Source License

/**
 * Returns an IR expression from the given JSON element.
 * //from   w  w  w .  ja  va 2s  .c  o m
 * @param json
 *            a JSON element (should be a primitive)
 * @return an expression, or <code>null</code>
 */
public Expression transformJson(JsonElement json) {
    if (json.isJsonPrimitive()) {
        JsonPrimitive primitive = json.getAsJsonPrimitive();
        if (primitive.isBoolean()) {
            return eINSTANCE.createExprBool(primitive.getAsBoolean());
        } else if (primitive.isNumber()) {
            return eINSTANCE.createExprInt(primitive.getAsBigInteger());
        } else if (primitive.isString()) {
            return eINSTANCE.createExprString(primitive.getAsString());
        }
    }
    return null;
}

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  . jav a 2  s. c  o  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.talvish.tales.serialization.json.translators.JsonObjectToPolymorphicObjectTranslator.java

License:Apache License

/**
 * Translates the received object into the appropriate json representation.
 * If the object is of the wrong type or the translator used doesn't produce
 * JsonElements's then a TranslationException will occur.
 *///w  w w .  ja v  a2  s  .c om
@Override
public Object translate(Object anObject) {
    Object returnValue;

    if (anObject == null || anObject.equals(JsonNull.INSTANCE)) {
        returnValue = null;
    } else {
        try {
            // need to extract two things, the "value" and the "value_type"
            // and if they don't exist then we have a problem
            JsonObject jsonObject = (JsonObject) anObject;
            JsonPrimitive valueTypeJson = jsonObject.getAsJsonPrimitive("value_type");
            JsonElement valueJson = jsonObject.get("value");

            if (valueTypeJson == null || !valueTypeJson.isString()) {
                throw new TranslationException(String.format("The associate value type is missing."));
            } else if (valueJson == null) {
                throw new TranslationException(String.format("The associate value for type '%s' is missing.",
                        valueTypeJson.getAsString()));
            } else {
                String valueTypeString = valueTypeJson.getAsString();
                TypeFormatAdapter typeAdapter = typeAdapters.get(valueTypeString);

                if (typeAdapter == null) {
                    throw new TranslationException(String
                            .format("Json is referring to a type '%s' that isn't supported.", valueTypeString));
                } else {
                    returnValue = typeAdapter.getFromFormatTranslator().translate(valueJson);
                }
            }

            // TODO: catch the various gson json exceptions
        } catch (ClassCastException e) {
            throw new TranslationException(e);
        }
    }
    return returnValue;
}

From source file:com.thoughtworks.go.plugin.access.configrepo.codec.TypeAdapter.java

License:Apache License

public <T> T determineJsonElementForDistinguishingImplementers(JsonElement json,
        JsonDeserializationContext context, String field, String origin) {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive prim = (JsonPrimitive) jsonObject.get(field);
    JsonPrimitive originField = (JsonPrimitive) jsonObject.get(origin);
    String typeName = prim.getAsString();

    Class<?> klass = classForName(typeName, originField == null ? null : originField.getAsString());
    return context.deserialize(jsonObject, klass);
}

From source file:com.thoughtworks.go.plugin.configrepo.codec.TypeAdapter.java

License:Apache License

public <T> T determineJsonElementForDistinguishingImplementers(JsonElement json,
        JsonDeserializationContext context, String field, String origin) {
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive prim = (JsonPrimitive) jsonObject.get(field);
    JsonPrimitive originField = (JsonPrimitive) jsonObject.get(origin);
    String typeName = prim.getAsString();

    Class<?> klass = classForName(typeName, originField == null ? "gocd" : originField.getAsString());
    return context.deserialize(jsonObject, klass);
}

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  ava  2 s .  c om*/
        } else {
            return n;
        }
    } else if (e.isBoolean()) {
        return e.getAsBoolean();
    } else {
        return e.getAsString();
    }
}

From source file:com.twitter.sdk.android.core.AuthTokenAdapter.java

License:Apache License

@Override
public AuthToken deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject jsonObject = json.getAsJsonObject();
    final JsonPrimitive jsonAuthType = jsonObject.getAsJsonPrimitive(AUTH_TYPE);
    final String authType = jsonAuthType.getAsString();
    final JsonElement jsonAuthToken = jsonObject.get(AUTH_TOKEN);
    return gson.fromJson(jsonAuthToken, authTypeRegistry.get(authType));
}