Example usage for com.google.gson JsonParseException JsonParseException

List of usage examples for com.google.gson JsonParseException JsonParseException

Introduction

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

Prototype

public JsonParseException(Throwable cause) 

Source Link

Document

Creates exception with the specified cause.

Usage

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   w w w  .  jav  a2  s.c o 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 ww w  . j  ava2  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.aad.adal.TokenCacheItemSerializationAdapater.java

License:Open Source License

private void throwIfParameterMissing(JsonObject json, String name) {
    if (!json.has(name)) {
        throw new JsonParseException(TAG + "Attribute " + name + " is missing for deserialization.");
    }// w  w  w.  j  av a 2  s  .  c o  m
}

From source file:com.microsoft.windowsazure.mobileservices.DateSerializer.java

License:Open Source License

/**
 * Deserializes an ISO-8601 formatted date
 *///from  w  w  w  .  ja v a2  s .c o  m
public static Date deserialize(String strVal) throws ParseException {
    // Change Z to +00:00 to adapt the string to a format
    // that can be parsed in Java
    String s = strVal.replace("Z", "+00:00");
    try {
        // Remove the ":" character to adapt the string to a
        // format
        // that can be parsed in Java
        s = s.substring(0, 26) + s.substring(27);
    } catch (IndexOutOfBoundsException e) {
        throw new JsonParseException("Invalid length");
    }

    // Parse the well-formatted date string
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSSZ");
    dateFormat.setTimeZone(TimeZone.getDefault());
    Date date = dateFormat.parse(s);

    return date;
}

From source file:com.microsoft.windowsazure.mobileservices.table.serialization.DateSerializer.java

License:Open Source License

/**
 * Deserializes an ISO-8601 formatted date
 *//*w  ww. ja  va2s .c  o  m*/
public static Date deserialize(String strVal) throws ParseException {

    String s = strVal;

    // Parse the well-formatted date string
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'.'SSSZ");
    dateFormat.setTimeZone(TimeZone.getDefault());

    try {

        String[] splittedByDot = strVal.split("\\.");

        if (splittedByDot.length == 1) {
            //We need to add the miliseconds
            s = s.replace("Z", ".000Z");
        } else {

            String miliseconds = splittedByDot[splittedByDot.length - 1].replace("Z", "");

            if (miliseconds.length() == 1) {
                miliseconds = "00" + miliseconds;
            } else if (miliseconds.length() == 2) {
                miliseconds = "0" + miliseconds;
            }

            s = splittedByDot[0] + "." + miliseconds + "Z";
        }

        // Change Z to +0000 to adapt the string to a format
        // that can be parsed in Java
        s = s.replace("Z", "+0000");

    } catch (IndexOutOfBoundsException e) {
        throw new JsonParseException("Invalid length");
    }

    Date date = dateFormat.parse(s);

    return date;
}

From source file:com.nimbits.server.gson.deserializer.DateDeserializer.java

License:Apache License

public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    try {//from   w  ww . j ava 2s  .  co m
        return format.parse(json.getAsJsonPrimitive().getAsString());
    } catch (ParseException e) {
        throw new JsonParseException(e.getMessage());
    }
}

From source file:com.paysafe.common.impl.BooleanAdapter.java

License:Open Source License

/**
 * Some api transactions will return 0 or 1 instead of the expected true or false.
 *
 * @param el the el/* ww  w.  j av a2s  . com*/
 * @param typeOfT the type of t
 * @param context the context
 * @return Boolean
 * @throws JsonParseException the json parse exception
 */
@Override
public Boolean deserialize(JsonElement el, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (((Class<?>) typeOfT).equals(Boolean.class)) {
        return el.getAsBoolean();
    } else if (((Class<?>) typeOfT).isInstance(Integer.class)) {
        final int elAsInt = el.getAsInt();
        if (elAsInt < 0 || elAsInt > 1) {
            throw new JsonParseException("Boolean out of range: " + elAsInt);
        }
        return elAsInt == 1;
    } else {
        throw new JsonParseException("Unexpected type: " + typeOfT);
    }
}

From source file:com.paysafe.common.impl.IdAdapter.java

License:Open Source License

@Override
public final Id<?> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!(typeOfT instanceof ParameterizedType)) {
        throw new JsonParseException("Unexpected type: " + typeOfT);
    }//from   w  w  w  . j  ava2s.com
    final ParameterizedType parameterizedType = (ParameterizedType) typeOfT;

    final Type typeOfId = parameterizedType.getActualTypeArguments()[0];

    @SuppressWarnings("unchecked")
    final Class<BaseDomainObject> clazz = (Class<BaseDomainObject>) typeOfId;
    return Id.create(json.getAsString(), clazz);
}

From source file:com.prayer.vakit.times.gson.RuntimeTypeAdapterFactory.java

License:Apache License

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

    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, 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.relayrides.pushy.apns.DateAsMillisecondsSinceEpochTypeAdapter.java

License:Open Source License

@Override
public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final Date date;

    if (json.isJsonPrimitive()) {
        date = new Date(json.getAsLong());
    } else if (json.isJsonNull()) {
        date = null;//from   w  ww.ja v a 2  s. c om
    } else {
        throw new JsonParseException(
                "Dates represented as seconds since the epoch must either be numbers or null.");
    }

    return date;
}