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.xpbytes.gson.hal.HalTypeAdapterFactory.java

License:Apache License

@Override
public <T> TypeAdapter<T> create(final Gson gson, final TypeToken<T> type) {

    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    final TypeAdapter<JsonElement> basicAdapter = gson.getAdapter(JsonElement.class);
    // If we convert to JSON, isn't the deserializer more appropriate...?

    // Is this a HalResource?
    if (!HalReflection.isResource(type.getRawType()))
        return delegate;

    return new TypeAdapter<T>() {
        @Override//from   ww  w .j a v a 2 s.  co m
        public void write(JsonWriter out, T value) throws IOException {
            delegate.write(out, value);
        }

        @Override
        public T read(JsonReader in) throws IOException {
            JsonElement fullJson = basicAdapter.read(in);
            Logger.getGlobal().log(Level.ALL, fullJson.toString());
            T deserialized = delegate.fromJsonTree(fullJson);

            if (fullJson.isJsonObject()) {
                JsonObject fullJsonObject = fullJson.getAsJsonObject();

                JsonObject linksObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_LINKS_ROOT);
                JsonObject embeddedObject = fullJsonObject.getAsJsonObject(HalConstants.RESERVED_EMBEDDED_ROOT);

                List<Field> fieldsList = HalReflection.getHalFields(type.getRawType());
                for (Field field : fieldsList) {
                    if (HalReflection.isLink(field))
                        readLink(field, linksObject, deserialized);
                    else if (HalReflection.isEmbed(field))
                        readEmbed(field, embeddedObject, deserialized);
                }

            }

            return deserialized;
        }

        private <A> void readEmbed(Field field, JsonObject rootObject, A deserialized) {
            HalEmbed embed = field.getAnnotation(HalEmbed.class);
            boolean optional = embed.optional();
            if (rootObject == null && optional)
                return;

            String memberName = HalReflection.getJsonFieldName(embed, field);
            JsonParseException missingException = new JsonParseException(
                    String.format(Locale.US, "Expected embed `%s` in the embedded root `%s` to be present",
                            memberName, HalConstants.RESERVED_EMBEDDED_ROOT));

            if (rootObject == null)
                throw missingException;

            boolean exists = rootObject.has(memberName);
            if (!exists) {
                if (optional)
                    return;
                throw missingException;
            }

            Type innerType = HalReflection.getFieldItemizedType(field);
            //Class outerType = HalReflection.getFieldType( field );
            JsonElement element = rootObject.get(memberName);

            // This gson.fromJson call will actually call into the proper stack to recursively
            // deserialize embeds and set their links where necessary.
            HalReflection.setEmbed(field, gson.fromJson(element, innerType), deserialized);
        }

        private <A> void readLink(Field field, JsonObject rootObject, A deserialized) {

            HalLink link = field.getAnnotation(HalLink.class);
            boolean optional = link.optional();
            if (rootObject == null && optional)
                return;

            String memberName = HalReflection.getJsonFieldName(link, field);
            JsonParseException missingException = new JsonParseException(
                    String.format(Locale.US, "Expected link `%s` in the links root `%s` to be present",
                            memberName, HalConstants.RESERVED_LINKS_ROOT));

            if (rootObject == null)
                throw missingException;

            boolean exists = rootObject.has(memberName);
            if (!exists) {
                if (optional)
                    return;
                throw missingException;
            }

            // If this is not a descendant of a HalLinkObject, we better treat it as one.
            Class<?> innerType = HalReflection.getFieldItemizedType(field);
            if (!innerType.isAssignableFrom(HalLinkObject.class))
                innerType = HalLinkObject.class;

            //Class outerType = HalReflection.getFieldType( field );
            JsonElement element = rootObject.get(memberName);

            // TODO support collections

            /*if ( Collection.class.isAssignableFrom( outerType ) )
            {
            innerType.
            //noinspection unchecked
            Class<Collection> collectionClass = (Class<Collection>)outerType;
            Collection collection = gson.fromJson( element, collectionClass );
            }
                    
            field.getType()
                    
            if ( element.isJsonArray() ) {
            for ( JsonElement element1 : element.getAsJsonArray() )
                HalReflection.setLink( field, , deserialized );
            } else {
             */
            HalReflection.setLink(field, (HalLinkObject) gson.fromJson(element, (Type) innerType),
                    deserialized);
        }

    }.nullSafe();
}

From source file:com.yandex.money.api.typeadapters.DateTimeTypeAdapter.java

License:Open Source License

@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    try {/*from   w w  w. j  a  v  a  2s.c  om*/
        return Iso8601Format.parse(json.getAsString());
    } catch (ParseException e) {
        throw new JsonParseException(e);
    }
}

From source file:com.yandex.money.api.typeadapters.model.showcase.FeeTypeAdapter.java

License:Open Source License

@Override
public Fee deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    String type = Delegate.getFeeType(json.getAsJsonObject());
    switch (type) {
    case TYPE_CUSTOM:
        return CustomFeeTypeAdapter.getInstance().fromJson(json);
    case TYPE_STD:
        return StdFeeTypeAdapter.getInstance().fromJson(json);
    default:/*from   w ww .j  av  a  2 s .c  om*/
        throw new JsonParseException("unknown fee type = " + type);
    }
}

From source file:com.zuiapps.suite.make.restful.JsonObjectConverter.java

License:Apache License

@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
    String charset = "UTF-8";
    if (body.mimeType() != null) {
        charset = MimeUtil.parseCharset(body.mimeType());
    }/*from  ww  w  . j  a  va  2  s  . c om*/
    try {
        String json = StringUtils.inputSteamToString(body.in(), charset);
        LogUtil.i("Json Object Converter", json);

        JSONObject jsonObject = new JSONObject(json);
        if (jsonObject.optInt("result") == 1) {
            if (jsonObject.has("data")) {
                JSONObject dataObj = jsonObject.optJSONObject("data");
                if (dataObj != null) {
                    return dataObj;
                } else {
                    JSONArray array = jsonObject.optJSONArray("data");
                    if (array != null) {
                        return array;
                    } else {
                        return new JSONObject();
                    }
                }
            } else {
                //               throw new ConversionException("No data object found.");
                return new JSONObject();
            }
        } else {
            throw new ConversionException("result is not true.");
        }

    } catch (IOException | JSONException e) {
        throw new ConversionException(e);
    } catch (JsonParseException e) {
        throw new JsonParseException(e);
    } finally {
        try {
            body.in().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:cz.boris.gson.typeadapter.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*from  www.j a  v  a  2 s.  c o  m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    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);
        }
    };
}

From source file:data.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson g, TypeToken<R> type) {
    if (type == null || !baseType.isAssignableFrom(type.getRawType()))
        return null;

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = g.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }/*from w  ww.  j av  a2s.c  om*/

    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:data_storage.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    // if (type.getRawType() != baseType) {
    // return null;
    // }/*from w  ww.j  a va 2s.c om*/

    if (!baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }
    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    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);
        }
    };
}

From source file:de.azapps.mirakel.model.list.meta.DueDeserializer.java

License:Open Source License

@Override
public SpecialListsDueProperty deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonObject()) {
        Integer length = 0, unit = 0;// initialize with stuff to mute the
        // compiler
        boolean negate = false; //set this as default to be backward compatible
        for (final Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            switch (entry.getKey()) {
            case "unit":
                if (entry.getValue().isJsonPrimitive()) {
                    unit = entry.getValue().getAsInt();
                    break;
                }//from ww w .jav a  2s.c  o m
                //$FALL-THROUGH$
            case "length":
                if (entry.getValue().isJsonPrimitive()) {
                    length = entry.getValue().getAsInt();
                    break;
                }
            case "negated":
                if (entry.getValue().isJsonPrimitive()) {
                    negate = entry.getValue().getAsBoolean();
                    break;
                }
                //$FALL-THROUGH$
            default:
                throw new JsonParseException("unknown format");
            }
        }
        if (unit != null && length != null) {
            return new SpecialListsDueProperty(Unit.values()[unit], length, negate);
        }
    }
    throw new JsonParseException("unknown format");
}

From source file:de.azapps.mirakel.model.list.meta.NegatedDeserializer.java

License:Open Source License

@Override
public T deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonObject()) {
        Boolean negated = null;// initialize with stuff to mute the
        // compiler
        for (final Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {

            if (entry.getValue().isJsonPrimitive() && ("done".equals(entry.getKey())
                    || "isSet".equals(entry.getKey()) || "isset".equals(entry.getKey()))) {
                negated = entry.getValue().getAsBoolean();
            } else {
                throw new JsonParseException("unknown format");
            }//from  w  ww .  j  av  a 2  s  .c  o  m
        }
        if (negated != null) {
            try {
                return (T) clazz.getConstructor(boolean.class).newInstance(negated);
            } catch (IllegalAccessException | InstantiationException | NoSuchMethodException
                    | InvocationTargetException e) {
                throw new JsonParseException("Could not create new SetProperty", e);
            }

        }
    }
    throw new JsonParseException("unknown format");
}

From source file:de.azapps.mirakel.model.list.meta.ProgressDeserializer.java

License:Open Source License

@Override
public SpecialListsProgressProperty deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonObject()) {
        Integer value = null, op = null;// initialize with stuff to mute the
        // compiler
        for (final Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            if (entry.getValue().isJsonPrimitive() && "value".equals(entry.getKey())) {
                value = entry.getValue().getAsInt();
            } else if (entry.getValue().isJsonPrimitive() && "op".equals(entry.getKey())) {
                op = entry.getValue().getAsInt();
            } else {
                throw new JsonParseException("unknown format");
            }//from   ww w  . j  av  a  2s  .co  m
        }
        if (value != null && op != null) {
            return new SpecialListsProgressProperty(value, OPERATION.values()[op]);
        }
    }
    throw new JsonParseException("unknown format");
}