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:abtlibrary.utils.as24ApiClient.JSON.java

License:Apache License

/**
 * Deserialize/*  ww w  .jav a2 s  . c om*/
 *
 * @param json Json element
 * @param date Type
 * @param typeOfSrc Type
 * @param context Json Serialization Context
 * @return Date
 * @throw JsonParseException if fail to parse
 */
@Override
public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context)
        throws JsonParseException {
    String str = json.getAsJsonPrimitive().getAsString();
    try {
        return apiClient.parseDateOrDatetime(str);
    } catch (RuntimeException e) {
        throw new JsonParseException(e);
    }
}

From source file:ar.com.ws.djnextension.config.GsonBuilderConfiguratorForTesting.java

License:Open Source License

/**
 * @param parent/*w  w  w  .j  a  v a  2 s. c om*/
 * @param elementName
 * @return
 */
private static int getIntValue(JsonObject parent, String elementName) {
    assert parent != null;
    assert !StringUtils.isEmpty(elementName);

    JsonElement element = parent.get(elementName);
    if (!element.isJsonPrimitive()) {
        throw new JsonParseException("Element + '" + elementName + "' must be a valid integer");
    }
    JsonPrimitive primitiveElement = (JsonPrimitive) element;
    if (!primitiveElement.isNumber()) {
        throw new JsonParseException("Element + '" + elementName + "' must be a valid integer");
    }
    return primitiveElement.getAsInt();
}

From source file:at.orz.arangodb.util.DateUtils.java

License:Apache License

/**
 * Parse date-string in "yyyy-MM-dd'T'HH:mm:ss'Z'" format.
 * @param dateString//from w  w w  .  j a v a2  s.c om
 * @return
 */
public static Date parse(String dateString) {

    try {
        return DateUtils.parse(dateString, "yyyy-MM-dd'T'HH:mm:ss'Z'");
    } catch (ParseException e) {
        throw new JsonParseException("time format invalid:" + dateString);
    }

}

From source file:blusunrize.immersiveengineering.common.crafting.RecipeFactoryShapelessIngredient.java

@Override
public IRecipe parse(JsonContext context, JsonObject json) {
    String group = JsonUtils.getString(json, "group", "");

    NonNullList<Ingredient> ings = NonNullList.create();
    for (JsonElement ele : JsonUtils.getJsonArray(json, "ingredients"))
        ings.add(CraftingHelper.getIngredient(ele, context));

    if (ings.isEmpty())
        throw new JsonParseException("No ingredients for shapeless recipe");

    ItemStack result = CraftingHelper.getItemStack(JsonUtils.getJsonObject(json, "result"), context);
    RecipeShapelessIngredient recipe = new RecipeShapelessIngredient(
            group.isEmpty() ? null : new ResourceLocation(group), result, ings);

    if (JsonUtils.hasField(json, "damage_tool"))
        recipe.setToolDamageRecipe(JsonUtils.getInt(json, "damage_tool"));
    if (JsonUtils.hasField(json, "copy_nbt"))
        recipe.setNBTCopyTargetRecipe(JsonUtils.getInt(json, "copy_nbt"));

    return recipe;
}

From source file:ca.oson.json.domain.PrimitiveTypeAdapter.java

License:Apache License

@SuppressWarnings("unchecked")
public <T> T adaptType(Object from, Class<T> to) {
    Class<?> aClass = Primitives.wrap(to);
    if (Primitives.isWrapperType(aClass)) {
        if (aClass == Character.class) {
            String value = from.toString();
            if (value.length() == 1) {
                return (T) (Character) from.toString().charAt(0);
            }//from   w  w  w . ja v a 2s  . c o  m
            throw new JsonParseException("The value: " + value + " contains more than a character.");
        }

        try {
            Constructor<?> constructor = aClass.getConstructor(String.class);
            return (T) constructor.newInstance(from.toString());
        } catch (NoSuchMethodException e) {
            throw new JsonParseException(e);
        } catch (IllegalAccessException e) {
            throw new JsonParseException(e);
        } catch (InvocationTargetException e) {
            throw new JsonParseException(e);
        } catch (InstantiationException e) {
            throw new JsonParseException(e);
        }
    } else if (Enum.class.isAssignableFrom(to)) {
        // Case where the type being adapted to is an Enum
        // We will try to convert from.toString() to the enum
        try {
            Method valuesMethod = to.getMethod("valueOf", String.class);
            return (T) valuesMethod.invoke(null, from.toString());
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    } else {
        throw new JsonParseException("Can not adapt type " + from.getClass() + " to " + to);
    }
}

From source file:ca.ualberta.CMPUT301W15T06.GsonAdapter.java

License:Apache License

@Override
public T deserialize(JsonElement json, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    // TODO Auto-generated method stub
    JsonObject jsonObject = json.getAsJsonObject();
    JsonPrimitive prim = (JsonPrimitive) jsonObject.get(CLASSNAME);
    String className = prim.getAsString();

    Class<?> klass = null;/*from w  w  w  .  j a v  a  2 s  .c  o m*/
    try {
        klass = Class.forName(className);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        throw new JsonParseException(e.getMessage());
    }
    return context.deserialize(jsonObject.get(INSTANCE), klass);
}

From source file:ca.ualberta.cs.team1travelexpenseapp.gsonUtils.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*  www .  ja va  2  s .  co 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:cc.kave.commons.utils.json.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }//w  w  w.ja  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);
            // (kave adaptation) was: ".remove(typeFiledName)"
            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 {
            if (value == null) {
                Streams.write(null, out);
                return;
            }
            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();
            // (kave adaptation) disabled check
            // 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:cl.niclabs.cb.common.MethodParser.java

License:Open Source License

@Override
public Method deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
        throws JsonParseException {
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    String method = jsonObject.get("method").getAsString();
    JsonElement argsJsonElement = jsonObject.get("args");
    switch (method) {
    case "OpenSession": {
        return methodFactory.makeOpenSessionMethod();
    }//  ww w.  j a v  a 2 s .co  m
    case "CloseSession": {
        CloseSessionMethod.Args args = context.deserialize(argsJsonElement, CloseSessionMethod.Args.class);
        return methodFactory.makeCloseSessionMethod(args);
    }
    case "DeleteKeyPair": {
        DeleteKeyPairMethod.Args args = context.deserialize(argsJsonElement, DeleteKeyPairMethod.Args.class);
        return methodFactory.makeDeleteKeyMethod(args);
    }
    case "GenerateKeyPair": {
        GenerateKeyPairMethod.Args args = context.deserialize(argsJsonElement,
                GenerateKeyPairMethod.Args.class);
        return methodFactory.makeGenerateKeyPairMethod(args);
    }
    case "SignInit": {
        SignInitMethod.Args args = context.deserialize(argsJsonElement, SignInitMethod.Args.class);
        return methodFactory.makeSignInitMethod(args);
    }
    case "Sign": {
        SignMethod.Args args = context.deserialize(argsJsonElement, SignMethod.Args.class);
        return methodFactory.makeSignMethod(args);
    }
    case "FindKey": {
        FindKeyMethod.Args args = context.deserialize(argsJsonElement, FindKeyMethod.Args.class);
        return methodFactory.makeFindKeyMethod(args);
    }
    case "SeedRandom": {
        SeedRandomMethod.Args args = context.deserialize(argsJsonElement, SeedRandomMethod.Args.class);
        return methodFactory.makeSeedRandomMethod(args);
    }
    case "GenerateRandom": {
        GenerateRandomMethod.Args args = context.deserialize(argsJsonElement, GenerateRandomMethod.Args.class);
        return methodFactory.makeGenerateRandomMethod(args);
    }
    case "DigestInit": {
        DigestInitMethod.Args args = context.deserialize(argsJsonElement, DigestInitMethod.Args.class);
        return methodFactory.makeDigestInitMethod(args);
    }
    case "Digest": {
        DigestMethod.Args args = context.deserialize(argsJsonElement, DigestMethod.Args.class);
        return methodFactory.makeDigestMethod(args);
    }
    default: {
        throw new JsonParseException("Cannot parse method: " + method);
    }
    }

}

From source file:cl.niclabs.tscrypto.common.messages.TSMessageParser.java

License:Open Source License

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

    JsonObject jobject = (JsonObject) json;
    String type = jobject.get("type").getAsString();
    String version = jobject.get("version").getAsString();

    // TODO check version

    if (type.equals("encrypted-data")) {
        return context.deserialize(json, EncryptedData.class);
    } else if (type.matches(".*-query")) {
        return parseQuery(type, version, json, context);
    } else if (type.matches(".*-answer")) {
        return parseAnswer(type, version, json, context);
    }/*from  w  ww . ja  va  2  s  . c  o  m*/

    throw new JsonParseException("Illegal TSMessage type/version:" + type + "/" + version);
}