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.contentful.java.cda.ResourceTypeAdapter.java

License:Apache License

/**
 * De-serialize a resource of type Entry. This method should return a {@code CDAEntry} object or
 * in case the resource matches a previously registered custom class via {@link
 * CDAClient.Builder#setCustomClasses(Map)}, an object of that custom class type will be created.
 *
 * @param jsonElement the resource in JSON form
 * @param context gson context/*  w w  w .  j a  v  a  2s.  c  o  m*/
 * @param sys map of system attributes
 * @return {@code CDAEntry} or a subclass of it
 */
private CDAEntry deserializeEntry(JsonElement jsonElement, JsonDeserializationContext context, JsonObject sys) {
    CDAEntry result;

    String contentTypeId = sys.get("contentType").getAsJsonObject().get("sys").getAsJsonObject().get("id")
            .getAsString();

    Class<?> clazz = customTypesMap.get(contentTypeId);

    if (clazz == null) {
        // Create a regular Entry, no custom class was registered.
        result = new CDAEntry();
    } else {
        // Use custom class registered for this Content Type.
        try {
            result = (CDAEntry) clazz.newInstance();
        } catch (InstantiationException e) {
            throw new JsonParseException(e);
        } catch (IllegalAccessException e) {
            throw new JsonParseException(e);
        }
    }

    setBaseFields(result, sys, jsonElement, context);
    return result;
}

From source file:com.davis.bluefolder.deserializers.DateDeserializer.java

@Override
public Date deserialize(JsonElement jsonElement, Type typeOF, JsonDeserializationContext context)
        throws JsonParseException {
    for (String format : DATE_FORMATS) {
        try {//from  ww  w  .  j  a v a 2 s. c  o  m
            return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
        } catch (ParseException e) {
        }
    }
    throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString() + "\". Supported formats: "
            + Arrays.toString(DATE_FORMATS));
}

From source file:com.devicehive.json.adapters.RuntimeTypeAdapterFactory.java

License:Apache License

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

    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);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().get(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);
            Streams.write(jsonObject, out);
        }
    }.nullSafe();
}

From source file:com.devicehive.websockets.WebSocketRequestProcessor.java

License:Apache License

public WebSocketResponse process(JsonObject request, WebSocketSession session) throws InterruptedException {
    WebSocketResponse response;/*from   ww w  .  java 2  s .  com*/
    WebsocketAction action = getAction(request);
    switch (action) {
    case SERVER_INFO:
        response = commonHandlers.processServerInfo(session);
        break;
    case AUTHENTICATE:
        response = commonHandlers.processAuthenticate(request, session);
        break;
    case TOKEN_REFRESH:
        response = commonHandlers.processRefresh(request, session);
        break;
    case NOTIFICATION_INSERT:
        response = notificationHandlers.processNotificationInsert(request, session);
        break;
    case NOTIFICATION_SUBSCRIBE:
        response = notificationHandlers.processNotificationSubscribe(request, session);
        break;
    case NOTIFICATION_UNSUBSCRIBE:
        response = notificationHandlers.processNotificationUnsubscribe(request, session);
        break;
    case COMMAND_INSERT:
        response = commandHandlers.processCommandInsert(request, session);
        break;
    case COMMAND_UPDATE:
        response = commandHandlers.processCommandUpdate(request, session);
        break;
    case COMMAND_SUBSCRIBE:
        response = commandHandlers.processCommandSubscribe(request, session);
        break;
    case COMMAND_UNSUBSCRIBE:
        response = commandHandlers.processCommandUnsubscribe(request, session);
        break;
    case DEVICE_GET:
        response = deviceHandlers.processDeviceGet(request);
        break;
    case DEVICE_SAVE:
        response = deviceHandlers.processDeviceSave(request, session);
        break;
    case EMPTY:
    default:
        throw new JsonParseException("'action' field could not be parsed to known endpoint");
    }
    return response;
}

From source file:com.epishie.tabs.gson.ThingDeserializer.java

License:Apache License

@Override
public Thing deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Expected json object");
    }//from ww  w. ja v  a 2  s  .  c o  m
    JsonObject jsonObject = json.getAsJsonObject();
    if (!jsonObject.has(KIND)) {
        throw new JsonParseException("Expected to have \"kind\" field");
    }
    JsonElement kindElement = jsonObject.get(KIND);
    if (!kindElement.isJsonPrimitive()) {
        throw new JsonParseException("Expected to have a primitive \"kind\" field");
    }
    if (!jsonObject.has(DATA)) {
        throw new JsonParseException("Expected to have a\"data\" field");
    }
    String kind = kindElement.getAsString();
    String id = null;
    String name = null;
    if (jsonObject.has(ID)) {
        JsonElement idElement = jsonObject.get(ID);
        id = idElement.getAsString();
    }
    if (jsonObject.has(NAME)) {
        JsonElement nameElement = jsonObject.get(NAME);
        name = nameElement.getAsString();
    }
    Thing thing = null;
    switch (kind) {
    case Link.KIND:
        Link link = context.deserialize(jsonObject.get(DATA), Link.class);
        thing = new Thing<>(id, name, link);
        break;
    case Listing.KIND:
        Listing listing = context.deserialize(jsonObject.get(DATA), Listing.class);
        // noinspection unchecked
        thing = new Thing(id, name, listing);
        break;
    case Subreddit.KIND:
        Subreddit subreddit = context.deserialize(jsonObject.get(DATA), Subreddit.class);
        // noinspection unchecked
        thing = new Thing(id, name, subreddit);
        break;
    case Comment.KIND:
        Comment comment = context.deserialize(jsonObject.get(DATA), Comment.class);
        // noinspection unchecked
        thing = new Thing(id, name, comment);
        break;
    }
    return thing;
}

From source file:com.etermax.conversations.repository.impl.elasticsearch.mapper.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }// w  w  w . j  a  v a2 s . com

    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);
        }
    }.nullSafe();
}

From source file:com.exsoloscript.challonge.gson.OffsetDateTimeAdapter.java

License:Apache License

@Override
public OffsetDateTime deserialize(JsonElement json, Type type,
        JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive();

    // if provided as String - '2011-12-03T10:15:30+01:00'
    if (jsonPrimitive.isString()) {
        return OffsetDateTime.parse(jsonPrimitive.getAsString(), DateTimeFormatter.ISO_OFFSET_DATE_TIME);
    }/*www . ja v  a2  s .  c  o m*/

    throw new JsonParseException("Unable to parse OffsetDateTime. DateTime was not provided as string.");
}

From source file:com.flipkart.batching.gson.RuntimeTypeAdapterFactory.java

License:Open Source License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//  ww  w.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 = labelToTypeAdapter.get(entry.getKey());
        if (delegate == null) {
            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 reader) throws IOException {

            if (reader.peek() == com.google.gson.stream.JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            if (reader.peek() != com.google.gson.stream.JsonToken.BEGIN_OBJECT) {
                reader.skipValue();
                return null;
            }
            reader.beginObject();

            String label = null;
            R result = null;
            while (reader.hasNext()) {
                String name = reader.nextName();
                com.google.gson.stream.JsonToken jsonToken = reader.peek();
                if (jsonToken == com.google.gson.stream.JsonToken.NULL) {
                    reader.skipValue();
                    continue;
                }
                switch (name) {
                case "type":
                    label = TypeAdapters.STRING.read(reader);
                    break;
                case "value":
                    @SuppressWarnings("unchecked") // registration requires that subtype extends T
                    TypeAdapter<R> delegate = label == null ? null
                            : (TypeAdapter<R>) labelToDelegate.get(label);
                    if (delegate == null) {
                        throw new JsonParseException("cannot deserialize " + baseType + " subtype named "
                                + label + "; did you forget to register a subtype?");
                    }
                    result = delegate.read(reader);
                    break;
                default:
                    reader.skipValue();
                    break;
                }
            }

            reader.endObject();
            return result;
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            @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?");
            }
            String label = subtypeToLabel.get(srcType);
            out.beginObject();

            out.name("type");
            out.value(label);

            out.name("value");
            delegate.write(out, value);

            out.endObject();
        }
    }.nullSafe();
}

From source file:com.github.autermann.matlab.json.MatlabRequestSerializer.java

License:Open Source License

private MatlabType parseType(JsonElement json) throws JsonParseException {
    String type = json.getAsString();
    try {/*ww w. j av  a2s.c  o m*/
        return MatlabType.fromString(type);
    } catch (IllegalArgumentException e) {
        throw new JsonParseException("Unknown type: " + type);
    }
}

From source file:com.github.autermann.matlab.json.MatlabValueSerializer.java

License:Open Source License

/**
 * Deserializes an {@link MatlabValue} from a {@link JsonElement}.
 *
 * @param element the <code>JsonElement</code> containing a
 *                serialized <code>MatlabValue</code>
 *
 * @return the deserialized <code>MatlabValue</code>
 *///from www .  j av a  2 s  . co m
public MatlabValue deserializeValue(JsonElement element) {
    if (!element.isJsonObject()) {
        throw new JsonParseException("expected JSON object");
    }
    JsonObject json = element.getAsJsonObject();
    MatlabType type = getType(json);
    JsonElement value = json.get(MatlabJSONConstants.VALUE);
    switch (type) {
    case ARRAY:
        return parseMatlabArray(value);
    case BOOLEAN:
        return parseMatlabBoolean(value);
    case CELL:
        return parseMatlabCell(value);
    case FILE:
        return parseMatlabFile(value);
    case MATRIX:
        return parseMatlabMatrix(value);
    case SCALAR:
        return parseMatlabScalar(value);
    case STRING:
        return parseMatlabString(value);
    case STRUCT:
        return parseMatlabStruct(value);
    case DATE_TIME:
        return parseMatlabDateTime(value);
    default:
        throw new JsonParseException("Unknown type: " + type);
    }
}