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:org.cinchapi.concourse.util.Convert.java

License:Open Source License

/**
 * Convert a JSON formatted string to a mapping that associates each key
 * with the Java objects that represent the corresponding values. This
 * method is designed to parse simple JSON structures that associate keys to
 * simple values or arrays without knowing the type of each element ahead of
 * time.//from www  .  ja v a 2 s.  c  o m
 * <p>
 * This method can properly handle JSON strings that abide by the following
 * rules:
 * <ul>
 * <li>The top level element in the JSON string must be an Object</li>
 * <li>No nested objects (e.g. a key cannot map to an object)</li>
 * <li>No null values</li>
 * </ul>
 * </p>
 * 
 * @param json
 * @return the converted data
 */
public static Multimap<String, Object> jsonToJava(String json) {
    // NOTE: in this method we use the #toString instead of the #getAsString
    // method of each JsonElement to trigger the conversion to a java
    // primitive to ensure that quotes are taken into account and we
    // properly convert strings masquerading as numbers (e.g. "3").
    Multimap<String, Object> data = LinkedHashMultimap.create();
    JsonParser parser = new JsonParser();
    JsonElement top = parser.parse(json);
    if (!top.isJsonObject()) {
        throw new JsonParseException("The JSON string must encapsulate data within an object");
    }
    JsonObject object = (JsonObject) parser.parse(json);
    for (Entry<String, JsonElement> entry : object.entrySet()) {
        String key = entry.getKey();
        JsonElement val = entry.getValue();
        if (val.isJsonArray()) {
            // If we have an array, add the elements individually. If there
            // are any duplicates in the array, they will be filtered out by
            // virtue of the fact that a LinkedHashMultimap does not store
            // dupes.
            Iterator<JsonElement> it = val.getAsJsonArray().iterator();
            while (it.hasNext()) {
                JsonElement elt = it.next();
                if (elt.isJsonPrimitive()) {
                    Object value = jsonElementToJava(elt);
                    data.put(key, value);
                } else {
                    throw new JsonParseException(
                            "Cannot parse a non-primitive " + "element inside of an array");
                }
            }
        } else {
            Object value = jsonElementToJava(val);
            data.put(key, value);
        }
    }
    return data;
}

From source file:org.cmg.jresp.json.AttributeDeserializer.java

License:Open Source License

@Override
public Attribute deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Unexpected JsonElement!");
    }//from www.j ava  2  s  .  c o  m
    JsonObject jo = (JsonObject) json;
    if ((!jo.has("name")) || (!jo.has("value"))) {
        throw new JsonParseException("Required attributes are not available!");
    }
    return new Attribute(jo.get("name").getAsString(), SCELJsonUtil.objectFromJson(jo.get("value"), context));
}

From source file:org.cmg.jresp.json.FormalTemplateFieldDeserializer.java

License:Open Source License

@Override
public FormalTemplateField deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Unexpected JsonElement!");
    }/*from   w ww .ja v  a2 s .c o  m*/
    JsonObject jo = (JsonObject) json;
    if ((!jo.has("type"))) {
        throw new JsonParseException("Required attributes are not available!");
    }
    try {
        Class<?> c = Class.forName(jo.get("type").getAsString());
        return new FormalTemplateField(c);
    } catch (ClassNotFoundException e) {
        throw new JsonParseException(e);
    }
}

From source file:org.cmg.jresp.json.SCELJsonUtil.java

License:Open Source License

/**
 * Deserialize an object from a {@link JsonElement}. We assume that the
 * received JsonElement is a {@link JsonObject} providing two attributes:
 * <ul>//from  w  w w . j a v  a 2  s  . c o m
 * <li><code>type</code>, containing a string with the fully qualified name
 * of the serialized object;
 * <li><code>value</code>, containing the {@link JsonElement} associated to
 * the serialized object.
 * </ul>
 * 
 * 
 * @param json
 *            element to deserialize
 * @param context
 *            context for serialization
 * @return the object represented by json
 */
public static Object objectFromJson(JsonElement json, JsonDeserializationContext context) {
    if (!json.isJsonObject()) {
        throw new JsonParseException("Unexpected JsonElement!");
    }
    JsonObject jo = (JsonObject) json;
    if ((!jo.has("type")) || (!jo.has("value"))) {
        throw new JsonParseException("Required attributes are not available!");
    }
    String className = jo.get(TYPE_ID).getAsString();
    try {
        Class<?> c = Class.forName(className);
        return context.deserialize(jo.get(VALUE_ID), c);
    } catch (ClassNotFoundException e) {
        throw new JsonParseException(e);
    }
}

From source file:org.cmg.jresp.json.TemplateDeserializer.java

License:Open Source License

@Override
public Template deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonArray()) {
        throw new JsonParseException("Unexpected JsonElement!");
    }/*from   w  w w .j a  va 2s  .c o  m*/
    JsonArray jsa = (JsonArray) json;
    TemplateField[] data = new TemplateField[jsa.size()];
    for (int i = 0; i < jsa.size(); i++) {
        try {
            data[i] = (TemplateField) SCELJsonUtil.objectFromJson(jsa.get(i), context);
        } catch (ClassCastException e) {
            throw new JsonParseException(e);
        }
    }
    return new Template(data);
}

From source file:org.cmg.jresp.json.TupleDeserializer.java

License:Open Source License

@Override
public Tuple deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    if (!json.isJsonArray()) {
        throw new JsonParseException("Unexpected JsonElement!");
    }//from w  ww  . jav  a  2  s.  c  om
    JsonArray jsa = (JsonArray) json;
    Object[] data = new Object[jsa.size()];
    for (int i = 0; i < jsa.size(); i++) {
        data[i] = SCELJsonUtil.objectFromJson(jsa.get(i), context);
    }
    return new Tuple(data);
}

From source file:org.codice.admin.router.RuntimeTypeAdapterFactory.java

License:Open Source License

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

From source file:org.commonjava.couch.io.json.CouchObjectListDeserializer.java

License:Apache License

@Override
public CouchObjectList<T> deserialize(final JsonElement json, final Type typeOfT,
        final JsonDeserializationContext context) throws JsonParseException {
    final boolean useDocElement = CouchDocument.class.isAssignableFrom(type);

    final List<T> items = new ArrayList<T>();

    final JsonElement rowsRaw = json.getAsJsonObject().get(ROWS);
    if (rowsRaw == null) {
        throw new JsonParseException("Cannot find " + ROWS + " field within root object.");
    }/*from w w w . ja v  a2  s .  co m*/

    final JsonArray rows = rowsRaw.getAsJsonArray();
    for (final JsonElement row : rows) {
        final JsonObject rowObj = row.getAsJsonObject();
        JsonElement data = rowObj;
        if (useDocElement) {
            data = rowObj.get(DOC_ELEMENT);
            if (data == null) {
                if (allowMissing) {
                    continue;
                }

                throw new JsonParseException("Cannot find " + DOC_ELEMENT + " field within row: " + row
                        + "\nDid you access the view with the '?include_docs=true' query parameter?");
            }
        }

        final Object val = context.deserialize(data, type);
        if (val != null) {
            items.add(type.cast(val));
        }
    }

    return new CouchObjectList<T>(items);
}

From source file:org.eclipse.jgit.diff.EditDeserializer.java

License:Apache License

@Override
public Edit deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context)
        throws JsonParseException {
    if (json.isJsonNull()) {
        return null;
    }//from  w  ww.  j a v  a 2 s  . com
    if (!json.isJsonArray()) {
        throw new JsonParseException("Expected array for Edit type");
    }

    final JsonArray o = (JsonArray) json;
    final int cnt = o.size();
    if (cnt < 4 || cnt % 4 != 0) {
        throw new JsonParseException("Expected array of 4 for Edit type");
    }

    if (4 == cnt) {
        return new Edit(get(o, 0), get(o, 1), get(o, 2), get(o, 3));
    }

    List<Edit> l = new ArrayList<>((cnt / 4) - 1);
    for (int i = 4; i < cnt;) {
        int as = get(o, i++);
        int ae = get(o, i++);
        int bs = get(o, i++);
        int be = get(o, i++);
        l.add(new Edit(as, ae, bs, be));
    }
    return new ReplaceEdit(get(o, 0), get(o, 1), get(o, 2), get(o, 3), l);
}

From source file:org.eclipse.jgit.diff.EditDeserializer.java

License:Apache License

private static int get(final JsonArray a, final int idx) throws JsonParseException {
    final JsonElement v = a.get(idx);
    if (!v.isJsonPrimitive()) {
        throw new JsonParseException("Expected array of 4 for Edit type");
    }//from  w  ww. j  a  v  a2s .  c o  m
    final JsonPrimitive p = (JsonPrimitive) v;
    if (!p.isNumber()) {
        throw new JsonParseException("Expected array of 4 for Edit type");
    }
    return p.getAsInt();
}