Example usage for com.google.gson JsonElement getAsString

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

Introduction

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

Prototype

public String getAsString() 

Source Link

Document

convenience method to get this element as a string value.

Usage

From source file:com.mediamath.terminalone.service.PostService.java

License:Apache License

private <T extends T1Entity> JsonResponse<? extends T1Entity> parsePostData(String response,
        T1JsonToObjParser parser, T entity) throws ParseException {

    // parse the string to gson objs
    JsonResponse<? extends T1Entity> finalJsonResponse = null;
    JsonElement element = parser.getDataFromResponse(response);
    if (element != null) {
        if (element.isJsonArray()) {
            // do something
            JsonArray dataList = element.getAsJsonArray();

            String entityType;/*from   w  ww. j a va  2  s. c om*/
            if (dataList.size() > 0) {
                JsonElement data = dataList.get(0);
                if (data != null) {
                    JsonObject dataObj = data.getAsJsonObject();
                    if (dataObj != null) {
                        JsonElement entityTypeElem = dataObj.get("entity_type");
                        if (entityTypeElem != null) {
                            entityType = entityTypeElem.getAsString();
                            if (entityType != null && !entityType.isEmpty()) {
                                if (Constants.getListoFEntityType.get(entityType) != null) {
                                    finalJsonResponse = parser.parseJsonToObj(response,
                                            Constants.getListoFEntityType.get(entityType));
                                }
                            }
                        }
                    }
                }
            }

        } else if (element.isJsonObject()) {
            JsonObject obj = element.getAsJsonObject();
            JsonElement entityTypeElement = obj.get("entity_type");
            String entityType = entityTypeElement.getAsString();
            finalJsonResponse = parser.parseJsonToObj(response, Constants.getEntityType.get(entityType));
        }
    } else if (element == null) {
        if (entity != null) {
            finalJsonResponse = parser.parseJsonToObj(response,
                    Constants.getEntityType.get(entity.getEntityname().toLowerCase()));
            if (finalJsonResponse != null) {
                finalJsonResponse.setData(null);
            }
        }
    }
    return finalJsonResponse;
}

From source file:com.mediamath.terminalone.TerminalOne.java

License:Apache License

/**
 * parses the response to objects.//from  ww w.  ja  va 2 s  .c o  m
 * 
 * @param response
 *          a valid JSON response string is required.
 * @param QueryCriteria
 *          a valid query object is required.
 * @return JsonResponse<? extends T1Entity> JsonResponse of type T is returned.
 * @throws ClientException
 *           a client exception is thrown if any error occurs.
 * @throws ParseException
 *           a parse exception is thrown when the response cannot be parsed.
 */
private <T extends T1Entity> JsonResponse<? extends T1Entity> parseGetData(String response, QueryCriteria query)
        throws ParseException, ClientException {
    T1JsonToObjParser parser = new T1JsonToObjParser();
    // parse the string to gson objs
    JsonResponse<? extends T1Entity> finalJsonResponse = null;
    JsonPostErrorResponse jsonPostErrorResponse = null;

    // check whether error present
    jsonPostErrorResponse = getService.jsonGetErrorResponseParser(response);
    // if no error
    if (jsonPostErrorResponse == null) {
        JsonElement element = parser.getDataFromResponse(response);
        if (element != null) {
            if (element.isJsonArray()) {
                // do something
                JsonArray dataList = element.getAsJsonArray();

                String entityType;
                if (dataList.size() > 0) {
                    JsonElement data = dataList.get(0);
                    if (data != null) {
                        JsonObject dataObj = data.getAsJsonObject();
                        if (dataObj != null) {
                            JsonElement entityTypeElem = dataObj.get("entity_type");
                            if (entityTypeElem != null) {
                                entityType = entityTypeElem.getAsString();
                                if (entityType != null && !entityType.isEmpty()) {
                                    if (Constants.getListoFEntityType.get(entityType) != null) {
                                        finalJsonResponse = parser.parseJsonToObj(response,
                                                Constants.getListoFEntityType.get(entityType));
                                    }
                                }
                            }
                        }
                    }
                } else {
                    if (query.collection != null) {
                        finalJsonResponse = parser.parseJsonToObj(response,
                                Constants.getListoFEntityType.get(query.collection.toLowerCase()));
                    }
                }

            } else if (element.isJsonObject()) {
                JsonObject obj = element.getAsJsonObject();
                JsonElement entityTypeElement = obj.get("entity_type");
                String entityType = (entityTypeElement != null) ? entityTypeElement.getAsString() : null;
                if (entityType != null && !entityType.equalsIgnoreCase("")) {
                    finalJsonResponse = parser.parseJsonToObj(response,
                            Constants.getEntityType.get(entityType));
                } else {
                    finalJsonResponse = parser.parseJsonToObj(response, new TypeToken<JsonResponse<Data>>() {
                    }.getType());
                }
            }
        } else if (element == null) {
            if (query.collection != null) {
                finalJsonResponse = parser.parseJsonToObj(response,
                        Constants.getEntityType.get(query.collection.toLowerCase()));
                if (finalJsonResponse != null) {
                    finalJsonResponse.setData(null);
                }
            }
        }
    } else {
        postService.throwExceptions(jsonPostErrorResponse);
    }
    return finalJsonResponse;
}

From source file:com.metinkale.prayerapp.vakit.times.gson.RuntimeTypeAdapterFactory.java

License:Apache License

@Override
public <R> TypeAdapter<R> create(@NonNull Gson gson, @NonNull TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//  w  ww  . jav a  2 s  .com

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, @NonNull R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    }.nullSafe();
}

From source file:com.michaelfotiadis.crossyscore.core.data.parsers.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(final Gson gson, final TypeToken<R> type) {
    if (!type.getRawType().equals(baseType)) {
        return null;
    }//www . j  av  a2  s  .  co  m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();

    for (final Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public void write(final JsonWriter out, final R value) throws IOException {
            if (value != null) {
                final Class<?> srcType = value.getClass();
                final String label = subtypeToLabel.get(srcType);
                @SuppressWarnings("unchecked")
                final // registration requires that subtype extends T
                TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
                if (delegate == null) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + "; did you forget to register a subtype?");
                }
                final JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
                if (jsonObject.has(typeFieldName)) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + " because it already defines a field named " + typeFieldName);
                }
                final JsonObject clone = new JsonObject();
                clone.add(typeFieldName, new JsonPrimitive(label));
                for (final Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                out.nullValue();
            }
        }

        @Override
        public R read(final JsonReader in) throws IOException {
            final JsonElement jsonElement = Streams.parse(in);
            // fix for null Json Elements
            if (jsonElement.isJsonNull()) {
                return null;
            }

            final JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            final String label = getBaseTypeLabel(labelJsonElement);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            final TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);

            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }

            return delegate.fromJsonTree(jsonElement);
        }

        private String getBaseTypeLabel(final JsonElement labelJsonElement) {
            final String label;

            if (labelJsonElement == null) {
                if (defaultSubTypeLabel == null) {
                    throw new JsonParseException("cannot deserialize " + baseType
                            + " because it does not define a field named " + typeFieldName);
                } else {
                    label = defaultSubTypeLabel;

                    if (!labelToDelegate.containsKey(label)) {
                        throw new IllegalStateException(
                                "WTF: Was looking for " + label + " in " + labelToDelegate.keySet());
                    }

                }
            } else {
                label = labelJsonElement.getAsString();
            }

            return label;
        }
    };
}

From source file:com.michaelfotiadis.steam.net.gson.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(final Gson gson, final TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//from  ww  w .ja v  a 2  s  . co m

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<>();

    for (final Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        final TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        private String getBaseTypeLabel(final JsonElement labelJsonElement) {
            final String label;

            if (labelJsonElement == null) {
                if (defaultSubTypeLabel == null) {
                    throw new JsonParseException("cannot deserialize " + baseType
                            + " because it does not define a field named " + typeFieldName);
                } else {
                    label = defaultSubTypeLabel;

                    if (!labelToDelegate.containsKey(label)) {
                        throw new IllegalStateException(
                                "WTF: Was looking for " + label + " in " + labelToDelegate.keySet());
                    }

                }
            } else {
                label = labelJsonElement.getAsString();
            }

            return label;
        }

        @Override
        public R read(final JsonReader in) throws IOException {
            final JsonElement jsonElement = Streams.parse(in);
            // fix for null Json Elements
            if (jsonElement.isJsonNull()) {
                return null;
            }

            final JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            final String label = getBaseTypeLabel(labelJsonElement);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            final TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);

            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }

            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(final JsonWriter out, final R value) throws IOException {
            if (value != null) {
                final Class<?> srcType = value.getClass();
                final String label = subtypeToLabel.get(srcType);
                @SuppressWarnings("unchecked")
                final // registration requires that subtype extends T
                TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
                if (delegate == null) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + "; did you forget to register a subtype?");
                }
                final JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
                if (jsonObject.has(typeFieldName)) {
                    throw new JsonParseException("cannot serialize " + srcType.getName()
                            + " because it already defines a field named " + typeFieldName);
                }
                final JsonObject clone = new JsonObject();
                clone.add(typeFieldName, new JsonPrimitive(label));
                for (final Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                    clone.add(e.getKey(), e.getValue());
                }
                Streams.write(clone, out);
            } else {
                out.nullValue();
            }
        }
    };
}

From source file:com.microsoft.aad.adal.DateTimeAdapter.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w w w . j av  a2 s  . c o m*/
 */
@Override
public synchronized Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    String jsonString = json.getAsString();

    // Datetime string is serialized with iso8601 format by default, should
    // always try to deserialize with iso8601. But to support the backward
    // compatibility, we also need to deserialize with old format if failing
    // with iso8601. 
    try {
        return mISO8601Format.parse(jsonString);
    } catch (final ParseException ignored) {
        Logger.v(TAG, "Cannot parse with ISO8601, try again with local format.");
    }

    // fallback logic for old date format parsing. 
    try {
        return mLocalFormat.parse(jsonString);
    } catch (final ParseException ignored) {
        Logger.v(TAG, "Cannot parse with local format, try again with local 24 hour format.");
    }

    try {
        return mLocal24HourFormat.parse(jsonString);
    } catch (final ParseException ignored) {
        Logger.v(TAG, "Cannot parse with local 24 hour format, try again with en us format.");
    }

    try {
        return mEnUsFormat.parse(jsonString);
    } catch (final ParseException ignored) {
        Logger.v(TAG, "Cannot parse with en us format, try again with en us 24 hour format.");
    }

    try {
        return mEnUs24HourFormat.parse(jsonString);
    } catch (final ParseException e) {
        Logger.e(TAG, "Could not parse date: " + e.getMessage(), "", ADALError.DATE_PARSING_FAILURE, e);
    }

    throw new JsonParseException("Could not parse date: " + jsonString);
}

From source file:com.microsoft.graph.serializer.GsonFactory.java

License:Open Source License

/**
 * Creates an instance of Gson.//from w  ww  .j  av a 2 s .  co  m
 *
 * @param logger The logger.
 * @return The new instance.
 */
public static Gson getGsonInstance(final ILogger logger) {

    final JsonSerializer<Calendar> calendarJsonSerializer = new JsonSerializer<Calendar>() {
        @Override
        public JsonElement serialize(final Calendar src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (src == null) {
                return null;
            }
            try {
                return new JsonPrimitive(CalendarSerializer.serialize(src));
            } catch (final Exception e) {
                logger.logError("Parsing issue on " + src, e);
                return null;
            }
        }
    };

    final JsonDeserializer<Calendar> calendarJsonDeserializer = new JsonDeserializer<Calendar>() {
        @Override
        public Calendar deserialize(final JsonElement json, final Type typeOfT,
                final JsonDeserializationContext context) throws JsonParseException {
            if (json == null) {
                return null;
            }
            try {
                return CalendarSerializer.deserialize(json.getAsString());
            } catch (final ParseException e) {
                logger.logError("Parsing issue on " + json.getAsString(), e);
                return null;
            }
        }
    };

    final JsonSerializer<byte[]> byteArrayJsonSerializer = new JsonSerializer<byte[]>() {
        @Override
        public JsonElement serialize(final byte[] src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (src == null) {
                return null;
            }
            try {
                return new JsonPrimitive(ByteArraySerializer.serialize(src));
            } catch (final Exception e) {
                logger.logError("Parsing issue on " + src, e);
                return null;
            }
        }
    };

    final JsonDeserializer<byte[]> byteArrayJsonDeserializer = new JsonDeserializer<byte[]>() {
        @Override
        public byte[] deserialize(final JsonElement json, final Type typeOfT,
                final JsonDeserializationContext context) throws JsonParseException {
            if (json == null) {
                return null;
            }
            try {
                return ByteArraySerializer.deserialize(json.getAsString());
            } catch (final ParseException e) {
                logger.logError("Parsing issue on " + json.getAsString(), e);
                return null;
            }
        }
    };

    final JsonSerializer<DateOnly> dateJsonSerializer = new JsonSerializer<DateOnly>() {
        @Override
        public JsonElement serialize(final DateOnly src, final Type typeOfSrc,
                final JsonSerializationContext context) {
            if (src == null) {
                return null;
            }
            return new JsonPrimitive(src.toString());
        }
    };

    final JsonDeserializer<DateOnly> dateJsonDeserializer = new JsonDeserializer<DateOnly>() {
        @Override
        public DateOnly deserialize(final JsonElement json, final Type typeOfT,
                final JsonDeserializationContext context) throws JsonParseException {
            if (json == null) {
                return null;
            }

            try {
                return DateOnly.parse(json.getAsString());
            } catch (final ParseException e) {
                logger.logError("Parsing issue on " + json.getAsString(), e);
                return null;
            }
        }
    };

    return new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
            .registerTypeAdapter(Calendar.class, calendarJsonSerializer)
            .registerTypeAdapter(Calendar.class, calendarJsonDeserializer)
            .registerTypeAdapter(GregorianCalendar.class, calendarJsonSerializer)
            .registerTypeAdapter(GregorianCalendar.class, calendarJsonDeserializer)
            .registerTypeAdapter(byte[].class, byteArrayJsonDeserializer)
            .registerTypeAdapter(byte[].class, byteArrayJsonSerializer)
            .registerTypeAdapter(DateOnly.class, dateJsonSerializer)
            .registerTypeAdapter(DateOnly.class, dateJsonDeserializer)
            .registerTypeAdapterFactory(new FallBackEnumTypeAdapter()).create();
}

From source file:com.microsoft.identity.client.internal.configuration.AzureActiveDirectoryAudienceDeserializer.java

License:Open Source License

@Override
public AzureActiveDirectoryAudience deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final String methodName = ":deserialize";
    JsonObject audienceObject = json.getAsJsonObject();
    JsonElement type = audienceObject.get("type");

    if (type != null) {
        switch (type.getAsString()) {
        case "AzureADMyOrg":
            Logger.verbose(TAG + methodName, "Type: AzureADMyOrg");
            return context.deserialize(audienceObject, AccountsInOneOrganization.class);
        case "AzureADMultipleOrgs":
            Logger.verbose(TAG + methodName, "Type: AzureADMultipleOrgs");
            return context.deserialize(audienceObject, AnyOrganizationalAccount.class);
        case "AzureADandPersonalMicrosoftAccount":
            Logger.verbose(TAG + methodName, "Type: AzureADandPersonalMicrosoftAccount");
            return context.deserialize(audienceObject, AllAccounts.class);
        case "PersonalMicrosoftAccount":
            Logger.verbose(TAG + methodName, "Type: PersonalMicrosoftAccount");
            return context.deserialize(audienceObject, AnyPersonalAccount.class);
        default://from ww  w  . ja v a  2s  . co  m
            Logger.verbose(TAG + methodName, "Type: Unknown");
            return context.deserialize(audienceObject, UnknownAudience.class);
        }
    }

    return null;
}

From source file:com.microsoft.identity.client.internal.configuration.LogLevelDeserializer.java

License:Open Source License

@Override
public Logger.LogLevel deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    return LogLevel.valueOf(json.getAsString().toUpperCase(Locale.US));
}

From source file:com.microsoft.onedrive.apiexplorer.DeltaFragment.java

License:Open Source License

/**
 * Create a handler for downloaded pages
 * @return The callback to handle a fresh DeltaPage
 *///w  ww . java  2s . c  o m
private ICallback<IDeltaCollectionPage> pageHandler() {
    return new DefaultCallback<IDeltaCollectionPage>(getActivity()) {
        @Override
        public void success(final IDeltaCollectionPage page) {
            final View view = getView();
            if (view == null) {
                return;
            }

            final View viewById = view.findViewById(R.id.json);
            if (viewById == null) {
                return;
            }

            if (mCurrentPagesCount.incrementAndGet() == MAX_PAGE_COUNT) {
                Toast.makeText(getActivity(), R.string.max_pages_downloaded, Toast.LENGTH_LONG).show();
                return;
            }

            final TextView jsonView = (TextView) viewById;
            final CharSequence originalText = jsonView.getText();
            final StringBuilder sb = new StringBuilder(originalText);
            for (final Item i : page.getCurrentPage()) {
                try {
                    final int indentSpaces = 3;
                    sb.append(new JSONObject(i.getRawObject().toString()).toString(indentSpaces));
                } catch (final JSONException ignored) {
                    Log.e(getClass().getName(), "Unable to parse the response body to json");
                }
                sb.append("\n");
            }

            if (page.getCurrentPage().size() == 0) {
                sb.append(getString(R.string.empty_delta));
            }
            jsonView.setText(sb.toString());
            view.findViewById(android.R.id.progress).setVisibility(View.INVISIBLE);
            jsonView.setVisibility(View.VISIBLE);
            if (page.getNextPage() != null) {
                page.getNextPage().buildRequest().get(pageHandler());
            }
            final JsonElement deltaToken = page.getRawObject().get("@delta.token");
            if (deltaToken != null) {
                getDeltaInfo().edit().putString(mItemId, deltaToken.getAsString()).commit();
            }
        }
    };
}