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:de.azapps.mirakel.model.list.meta.SetDeserializer.java

License:Open Source License

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

            if (entry.getValue().isJsonArray() && "content".equals(entry.getKey())) {
                content = new ArrayList<>(entry.getValue().getAsJsonArray().size());
                for (final JsonElement el : ((JsonArray) entry.getValue())) {
                    if (el.isJsonPrimitive() && el.getAsJsonPrimitive().isNumber()) {
                        content.add(el.getAsInt());
                    }/*from   ww w . jav  a2s .  co m*/
                }
            } else if (entry.getValue().isJsonPrimitive()
                    && ("isNegated".equals(entry.getKey()) || "isSet".equals(entry.getKey()))) {
                negated = entry.getValue().getAsBoolean();
            } else {
                throw new JsonParseException("unknown format");
            }
        }
        if ((content != null) && (negated != null)) {
            try {
                return (T) clazz.getConstructor(boolean.class, List.class).newInstance(negated, content);
            } 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.StringDeserializer.java

License:Open Source License

@Override
public T deserialize(final JsonElement json, final java.lang.reflect.Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    if (json.isJsonObject()) {
        Integer type = null;// initialize with stuff to quite compiler
        String searchString = null;
        Boolean negated = null;//w ww . ja v  a  2  s  . co  m
        for (final Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) {
            switch (entry.getKey()) {
            case "isNegated":
            case "isSet":
                if (entry.getValue().isJsonPrimitive()) {
                    negated = entry.getValue().getAsBoolean();
                    break;
                }
                //$FALL-THROUGH$
            case "type":
                if (entry.getValue().isJsonPrimitive()) {
                    type = entry.getValue().getAsInt();
                    break;
                }
                //$FALL-THROUGH$
            case "searchString":
            case "serachString"://this must be here
                if (entry.getValue().isJsonPrimitive()) {
                    searchString = entry.getValue().getAsString();
                    break;
                }
                //$FALL-THROUGH$
            default:
                throw new JsonParseException("unknown format");
            }
        }
        if (((searchString != null) & (type != null)) && (negated != null)) {

            try {
                return (T) clazz.getConstructor(boolean.class, String.class, Type.class).newInstance(negated,
                        searchString, Type.values()[type]);
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException
                    | NoSuchMethodException e) {
                throw new JsonParseException("Could not create new StringProperty", e);
            }
        }
    }
    throw new JsonParseException("unknown format");
}

From source file:de.azapps.mirakel.model.task.TaskDeserializer.java

License:Open Source License

@Override
public Task deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    final JsonObject el = json.getAsJsonObject();
    Optional<ListMirakel> taskList = absent();
    final JsonElement id = el.get("id");
    if (id == null) {
        throw new JsonParseException("Json malformed");
    }/*from w w  w. j  a  v a 2 s. c o m*/
    final Task task = Task.get(id.getAsLong()).or(new Task());
    // Name
    final Set<Entry<String, JsonElement>> entries = el.entrySet();
    for (final Entry<String, JsonElement> entry : entries) {
        final String key = entry.getKey();
        final JsonElement val = entry.getValue();
        if ((key == null) || "id".equalsIgnoreCase(key)) {
            continue;
        }
        switch (key.toLowerCase()) {
        case "name":
            task.setName(val.getAsString());
            break;
        case "content":
            String content = val.getAsString();
            if (content == null) {
                content = "";
            }
            task.setContent(content);
            break;
        case "priority":
            task.setPriority((int) val.getAsFloat());
            break;
        case "progress":
            task.setProgress((int) val.getAsDouble());
            break;
        case "list_id":
            taskList = ListMirakel.get(val.getAsInt());
            if (!taskList.isPresent()) {
                taskList = fromNullable(SpecialList.firstSpecialSafe().getDefaultList());
            }
            break;
        case "created_at":
            try {
                task.setCreatedAt(DateTimeHelper.parseDateTime(val.getAsString().replace(":", "")));
            } catch (final ParseException e) {
                Log.wtf(TAG, "invalid dateformat: ", e);
            }
            break;
        case "updated_at":
            try {
                task.setUpdatedAt(DateTimeHelper.parseDateTime(val.getAsString().replace(":", "")));
            } catch (final ParseException e) {
                Log.wtf(TAG, "invalid dateformat: ", e);
            }
            break;
        case "done":
            task.setDone(val.getAsBoolean());
            break;
        case "due":
            try {
                task.setDue(of(DateTimeHelper.createLocalCalendar(val.getAsLong())));
            } catch (final NumberFormatException ignored) {
                task.setDue(Optional.<Calendar>absent());
            }
            break;
        case "reminder":
            try {
                task.setReminder(of(DateTimeHelper.createLocalCalendar(val.getAsLong())));
            } catch (final NumberFormatException ignored) {
                task.setReminder(Optional.<Calendar>absent());
            }
            break;
        case "tags":
            handleTags(task, val);
            break;
        case "sync_state":
            task.setSyncState(DefinitionsHelper.SYNC_STATE.valueOf((short) val.getAsFloat()));
            break;
        case "show_recurring":
            task.setIsRecurringShown(val.getAsBoolean());
            break;
        default:
            handleAdditionalEntries(task, key, val);
            break;
        }
    }
    if (!taskList.isPresent()) {
        taskList = of(ListMirakel.safeFirst());
    }
    task.setList(taskList.get(), true);
    return task;
}

From source file:de.azapps.mirakel.sync.taskwarrior.model.TaskWarriorTaskDeserializer.java

License:Open Source License

@Override
public TaskWarriorTask deserialize(final JsonElement json, final Type type,
        final JsonDeserializationContext ctx) throws JsonParseException {
    final JsonObject el = json.getAsJsonObject();
    final JsonElement uuid = el.get("uuid");
    final JsonElement status = el.get("status");
    final JsonElement entry = el.get("entry");
    final JsonElement description = el.get("description");
    if (uuid == null || status == null || entry == null || description == null || !uuid.isJsonPrimitive()
            || !status.isJsonPrimitive() || !entry.isJsonPrimitive() || !description.isJsonPrimitive()
            || !uuid.getAsJsonPrimitive().isString() || !status.getAsJsonPrimitive().isString()
            || !entry.getAsJsonPrimitive().isString() || !description.getAsJsonPrimitive().isString()) {
        throw new JsonParseException("Invalid syntax, missing required field");
    }//from  w  ww.j a va2 s . c  o  m
    final TaskWarriorTask task = new TaskWarriorTask(uuid.getAsString(), status.getAsString(),
            parseDate(entry.getAsString()), description.getAsString());
    for (final Entry<String, JsonElement> element : el.entrySet()) {
        switch (element.getKey()) {
        case "uuid":
        case "description":
        case "entry":
        case "status":
            break;
        case "priority":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setPriority(element.getValue().getAsString());
            } else {
                throw new JsonParseException("priority is not a json primitive");
            }
            break;
        case "priorityNumber":
            // taskd does not handle numbers in the right way
            if (element.getValue().isJsonPrimitive()) {
                task.setPriorityNumber((int) element.getValue().getAsDouble());
            } else {
                throw new JsonParseException("priority is not a json primitive");
            }
            break;
        case "progress":
            // taskd does not handle numbers in the right way
            if (element.getValue().isJsonPrimitive()) {
                task.setProgress((int) element.getValue().getAsDouble());
            } else {
                throw new JsonParseException("progress is not a json primitive");
            }
            break;
        case "project":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setProject(element.getValue().getAsString());
            } else {
                throw new JsonParseException("project is not a json primitive");
            }
            break;
        case "modification":
        case "modified":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setModified(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("modified is not a json primitive");
            }
            break;
        case "due":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setDue(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("due is not a json primitive");
            }
            break;
        case "reminder":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setReminder(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("reminder is not a json primitive");
            }
            break;
        case "annotations":
            if (element.getValue().isJsonArray()) {
                final JsonArray annotations = element.getValue().getAsJsonArray();
                for (int i = 0; i < annotations.size(); i++) {
                    if (annotations.get(i).isJsonObject()) {
                        final JsonElement descr = annotations.get(i).getAsJsonObject().get("description");
                        final JsonElement annotationEntry = annotations.get(i).getAsJsonObject().get("entry");
                        if (descr == null || annotationEntry == null || !descr.isJsonPrimitive()
                                || !annotationEntry.isJsonPrimitive() || !descr.getAsJsonPrimitive().isString()
                                || !annotationEntry.getAsJsonPrimitive().isString()) {
                            throw new JsonParseException("Annotation is not valid");
                        } else {
                            task.addAnnotation(descr.getAsString(), parseDate(annotationEntry.getAsString()));
                        }
                    } else {
                        throw new JsonParseException("Annotation is not a json object");
                    }
                }
            } else {
                throw new JsonParseException("annotations is not a json array");
            }
            break;
        case "depends":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                final String depends = element.getValue().getAsString();
                task.addDepends(depends.split(","));
            } else {
                throw new JsonParseException("depends is not a json primitive");
            }
            break;
        case "tags":
            if (element.getValue().isJsonArray()) {
                final JsonArray tags = element.getValue().getAsJsonArray();
                for (int i = 0; i < tags.size(); i++) {
                    if (tags.get(i).isJsonPrimitive() && tags.get(i).getAsJsonPrimitive().isString()) {
                        task.addTags(tags.get(i).getAsString());
                    } else {
                        throw new JsonParseException("tag is not a string");
                    }
                }
            } else {
                throw new JsonParseException("tags is not a json array");
            }
            break;
        case "recur":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setRecur(element.getValue().getAsString());
            } else {
                throw new JsonParseException("recur is not a json primitive");
            }
            break;
        case "imask":
            if (element.getValue().isJsonPrimitive()) {
                task.setImask((int) element.getValue().getAsDouble());
            } else {
                throw new JsonParseException("imask is not a json primitive");
            }
            break;
        case "parent":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setParent(element.getValue().getAsString());
            } else {
                throw new JsonParseException("parent is not a json primitive");
            }
            break;
        case "mask":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setMask(element.getValue().getAsString());
            } else {
                throw new JsonParseException("mask is not a json primitive");
            }
            break;
        case "until":
            if (element.getValue().isJsonPrimitive() && element.getValue().getAsJsonPrimitive().isString()) {
                task.setUntil(parseDate(element.getValue().getAsString()));
            } else {
                throw new JsonParseException("until is not a json primitive");
            }
            break;
        default:
            task.addUDA(element.getKey(), element.getValue().getAsString());
            break;
        }
    }

    return task;
}

From source file:de.bwravencl.controllerbuddy.json.ActionTypeAdapter.java

License:Open Source License

private static JsonElement get(final JsonObject wrapper, final String memberName) {
    final var jsonElement = wrapper.get(memberName);
    if (jsonElement == null)
        throw new JsonParseException(
                "No member '" + memberName + "' found in what was expected to be an interface wrapper");

    return jsonElement;
}

From source file:de.bwravencl.controllerbuddy.json.ActionTypeAdapter.java

License:Open Source License

@Override
public IAction<?> deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final var wrapper = json.getAsJsonObject();
    final var typeName = get(wrapper, PROPERTY_TYPE);
    final var typeNameString = typeName.getAsString();
    final var data = get(wrapper, PROPERTY_DATA);

    try {//from  w  w w  . jav  a  2 s .  co  m
        final var actualType = Class.forName(typeNameString);
        return context.deserialize(data, actualType);
    } catch (final ClassNotFoundException e) {
        if (typeOfT == IAction.class) {
            log.log(Logger.Level.WARNING, "Action class '" + typeNameString + "' not found, substituting with '"
                    + NullAction.class.getSimpleName() + "'");
            unknownActionClasses.add(typeNameString);

            return new NullAction();
        }

        throw new JsonParseException(e);
    }
}

From source file:de.chefkoch.api.serialize.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 v  a2s  . 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 null;
            }
            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.justi.yagw2api.common.json.TupleTypeAdapter.java

License:Apache License

@Override
public Tuple deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    if (!(json instanceof JsonArray)) {
        throw new JsonParseException("The tuple should be a json array but was " + json.getClass());
    }/*from www. j  av  a 2 s. c o m*/
    final JsonArray jsonArray = (JsonArray) json;
    final ImmutableList.Builder<?> tupleParts = ImmutableList.builder();
    for (JsonElement element : jsonArray) {
        tupleParts.add(context.deserialize(element, Object.class));
    }
    return Tuples.from(tupleParts.build());
}

From source file:de.lulebe.designer.external.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type == null || !baseType.isAssignableFrom(type.getRawType())) {
        return null;
    }//  ww w.  j a  va 2s.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);
        }
    }.nullSafe();
}

From source file:de.sanandrew.mods.sanlib.lib.util.JsonUtils.java

License:Creative Commons License

private static ItemStack getStack(JsonObject jsonObj) {
    String itemName = net.minecraft.util.JsonUtils.getString(jsonObj, "item");
    Item item = ForgeRegistries.ITEMS.getValue(new ResourceLocation(itemName));

    if (item == null) {
        throw new JsonParseException(String.format("Unknown item '%s'", itemName));
    }//from  w  w  w .ja  v  a 2  s. co m

    if (item.getHasSubtypes() && !jsonObj.has("data")) {
        throw new JsonParseException(String.format("Missing data for item '%s'", itemName));
    }

    ItemStack stack;
    if (jsonObj.has("nbt")) {
        try {
            NBTTagCompound nbt = JsonToNBT.getTagFromJson(GSON.toJson(jsonObj.get("nbt")));
            NBTTagCompound tmp = new NBTTagCompound();
            if (nbt.hasKey("ForgeCaps")) {
                tmp.setTag("ForgeCaps", nbt.getTag("ForgeCaps"));
                nbt.removeTag("ForgeCaps");
            }

            tmp.setTag("tag", nbt);
            tmp.setString("id", itemName);
            tmp.setInteger("Count", net.minecraft.util.JsonUtils.getInt(jsonObj, "count", 1));
            tmp.setInteger("Damage", net.minecraft.util.JsonUtils.getInt(jsonObj, "data", 0));

            stack = new ItemStack(tmp);
        } catch (NBTException e) {
            throw new JsonParseException("Invalid NBT Entry: " + e.toString());
        }
    } else {
        stack = new ItemStack(item, net.minecraft.util.JsonUtils.getInt(jsonObj, "count", 1),
                net.minecraft.util.JsonUtils.getInt(jsonObj, "data", 0));
    }

    if (!ItemStackUtils.isValid(stack)) {
        throw new JsonParseException("Invalid Item: " + stack.toString());
    }

    return stack;
}