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.ccc.crest.core.cache.crest.Paging.java

License:Open Source License

protected void pagingDeserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Iterator<Entry<String, JsonElement>> objectIter = ((JsonObject) json).entrySet().iterator();
    while (objectIter.hasNext()) {
        Entry<String, JsonElement> objectEntry = objectIter.next();
        String key = objectEntry.getKey();
        JsonElement value = objectEntry.getValue();
        if (pagingDeserialize(key, value))
            continue;
        if (ItemsKey.equals(key)) {
            JsonElement objectElement = objectEntry.getValue();
            if (!objectElement.isJsonArray())
                throw new JsonParseException(
                        "Expected " + ItemsKey + " array received json element " + objectElement.toString());
            int size = ((JsonArray) objectElement).size();
            for (int i = 0; i < size; i++) {
                JsonElement childElement = ((JsonArray) objectElement).get(i);
                items.add(getPagedItem(childElement, typeOfT, context));
            }//from   www. j a va 2s  .  c  o m
        } else
            LoggerFactory.getLogger(getClass())
                    .warn(key + " has a field not currently being handled: \n" + objectEntry.toString());
    }
}

From source file:com.ccc.crest.core.cache.crest.schema.option.Representations.java

License:Open Source License

@Override
public Representations deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Iterator<Entry<String, JsonElement>> objectIter = ((JsonObject) json).entrySet().iterator();
    while (objectIter.hasNext()) {
        Entry<String, JsonElement> objectEntry = objectIter.next();
        String key = objectEntry.getKey();
        JsonElement value = objectEntry.getValue();
        if (RepresentationsKey.equals(key)) {
            JsonElement objectElement = objectEntry.getValue();
            if (!objectElement.isJsonArray())
                throw new JsonParseException("Expected " + RepresentationsKey + " array received json element "
                        + objectElement.toString());
            int size = ((JsonArray) objectElement).size();
            for (int i = 0; i < size; i++) {
                JsonElement childElement = ((JsonArray) objectElement).get(i);
                Representation representation = new Representation();
                representations.add(representation);
                representation.deserialize(childElement, typeOfT, context);
            }/*from w w  w. ja v a2s . c  o m*/
        } else
            LoggerFactory.getLogger(getClass())
                    .warn(key + " has a field not currently being handled: \n" + objectEntry.toString());
    }
    return this;
}

From source file:com.ccc.crest.core.cache.crest.tournament.Bans.java

License:Open Source License

@Override
public Bans deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Iterator<Entry<String, JsonElement>> objectIter = ((JsonObject) json).entrySet().iterator();
    while (objectIter.hasNext()) {
        Entry<String, JsonElement> objectEntry = objectIter.next();
        String key = objectEntry.getKey();
        JsonElement value = objectEntry.getValue();
        if (SelfKey.equals(key)) {
            self = new ExternalRef();
            self.deserialize(value, typeOfT, context);
        } else if (RedKey.equals(key)) {
            JsonElement objectElement = objectEntry.getValue();
            if (!objectElement.isJsonArray())
                throw new JsonParseException(
                        "Expected " + RedKey + " array received json element " + objectElement.toString());
            int size = ((JsonArray) objectElement).size();
            for (int i = 0; i < size; i++) {
                JsonElement childElement = ((JsonArray) objectElement).get(i);
                Ban child = new Ban();
                redTeam.add(child);//ww  w  . j av a  2 s  .c om
                child.deserialize(childElement, typeOfT, context);
            }
        } else if (BlueKey.equals(key)) {
            JsonElement objectElement = objectEntry.getValue();
            if (!objectElement.isJsonArray())
                throw new JsonParseException(
                        "Expected " + BlueKey + " array received json element " + objectElement.toString());
            int size = ((JsonArray) objectElement).size();
            for (int i = 0; i < size; i++) {
                JsonElement childElement = ((JsonArray) objectElement).get(i);
                Ban child = new Ban();
                blueTeam.add(child);
                child.deserialize(childElement, typeOfT, context);
            }
        } else
            LoggerFactory.getLogger(getClass())
                    .warn(key + " has a field not currently being handled: \n" + objectEntry.toString());
    }
    return this;
}

From source file:com.ccc.crest.core.cache.crest.tournament.Series.java

License:Open Source License

@Override
public Series deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Iterator<Entry<String, JsonElement>> objectIter = ((JsonObject) json).entrySet().iterator();
    while (objectIter.hasNext()) {
        Entry<String, JsonElement> objectEntry = objectIter.next();
        String key = objectEntry.getKey();
        JsonElement value = objectEntry.getValue();
        if (SeriesUrlKey.equals(key)) {
            seriesUrl = new ExternalRef();
            seriesUrl.deserialize(value, typeOfT, context);
        } else if (TypeKey.equals(key))
            type = value.getAsString();/*from w w w  .ja  va  2 s  .  co  m*/
        else if (NameKey.equals(key))
            name = value.getAsString();
        else if (TeamStatsKey.equals(key)) {
            JsonElement objectElement = objectEntry.getValue();
            if (!objectElement.isJsonArray())
                throw new JsonParseException("Expected " + TeamStatsKey + " array received json element "
                        + objectElement.toString());
            int size = ((JsonArray) objectElement).size();
            for (int i = 0; i < size; i++) {
                JsonElement childElement = ((JsonArray) objectElement).get(i);
                TeamStats child = new TeamStats();
                teamStats.add(child);
                child.deserialize(childElement, typeOfT, context);
            }
        } else
            LoggerFactory.getLogger(getClass())
                    .warn(key + " has a field not currently being handled: \n" + objectEntry.toString());
    }
    return this;
}

From source file:com.ccc.crest.core.cache.crest.tournament.SeriesElement.java

License:Open Source License

@Override
public SeriesElement deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Iterator<Entry<String, JsonElement>> objectIter = ((JsonObject) json).entrySet().iterator();
    while (objectIter.hasNext()) {
        Entry<String, JsonElement> objectEntry = objectIter.next();
        String key = objectEntry.getKey();
        JsonElement value = objectEntry.getValue();
        if (TotalCountStrKey.equals(key))
            totalCountStr = value.getAsString();
        else if (ItemsKey.equals(key)) {
            JsonElement objectElement = objectEntry.getValue();
            if (!objectElement.isJsonArray())
                throw new JsonParseException(
                        "Expected " + ItemsKey + " array received json element " + objectElement.toString());
            int size = ((JsonArray) objectElement).size();
            for (int i = 0; i < size; i++) {
                JsonElement childElement = ((JsonArray) objectElement).get(i);
                TeamInfo child = new TeamInfo();
                teamInfos.add(child);/*from   w w  w  . j a  va2s. co m*/
                child.deserialize(childElement, typeOfT, context);
            }
        } else if (PageCountKey.equals(key))
            pageCount = value.getAsLong();
        else if (PageCountStrKey.equals(key))
            pageCountStr = value.getAsString();
        else if (TotalCountKey.equals(key))
            totalCount = value.getAsLong();
        else
            LoggerFactory.getLogger(getClass())
                    .warn(key + " has a field not currently being handled: \n" + objectEntry.toString());
    }
    return this;
}

From source file:com.ccc.crest.core.cache.crest.tournament.Tournaments.java

License:Open Source License

@Override
public Tournaments deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
    Iterator<Entry<String, JsonElement>> objectIter = ((JsonObject) json).entrySet().iterator();
    while (objectIter.hasNext()) {
        Entry<String, JsonElement> objectEntry = objectIter.next();
        String key = objectEntry.getKey();
        JsonElement value = objectEntry.getValue();
        if (TotalCountStringKey.equals(key))
            totalCountStr = value.getAsString();
        else if (ItemsKey.equals(key)) {
            JsonElement objectElement = objectEntry.getValue();
            if (!objectElement.isJsonArray())
                throw new JsonParseException(
                        "Expected " + ItemsKey + " array received json element " + objectElement.toString());
            int size = ((JsonArray) objectElement).size();
            for (int i = 0; i < size; i++) {
                JsonElement childElement = ((JsonArray) objectElement).get(i);
                Tournament child = new Tournament();
                tournaments.add(child);/*from   w  w  w .ja v  a  2  s  .c om*/
                child.deserialize(childElement, typeOfT, context);
            }
        } else if (PageCountKey.equals(key))
            pageCount = value.getAsLong();
        else if (PageCountStringKey.equals(key))
            pageCountStr = value.getAsString();
        else if (TotalCountKey.equals(key))
            totalCount = value.getAsLong();
        else
            LoggerFactory.getLogger(getClass())
                    .warn(key + " has a field not currently being handled: \n" + objectEntry.toString());
    }
    return this;
}

From source file:com.cinchapi.concourse.util.Convert.java

License:Apache License

/**
 * Takes a JSON string representation of an object or an array of JSON
 * objects and returns a list of {@link Multimap multimaps} with the
 * corresponding data. Unlike {@link #jsonToJava(String)}, this method will
 * allow the top level element to be an array in the {code json} string.
 * //from   ww w  . j a v  a2 s. c o  m
 * @param json
 * @return A list of Java objects
 */
public static List<Multimap<String, Object>> anyJsonToJava(String json) {
    List<Multimap<String, Object>> result = Lists.newArrayList();
    try (JsonReader reader = new JsonReader(new StringReader(json))) {
        reader.setLenient(true);
        if (reader.peek() == JsonToken.BEGIN_ARRAY) {
            try {
                reader.beginArray();
                while (reader.peek() != JsonToken.END_ARRAY) {
                    result.add(jsonToJava(reader));
                }
                reader.endArray();
            } catch (IllegalStateException e) {
                throw new JsonParseException(e.getMessage());
            }
        } else {
            result.add(jsonToJava(reader));
        }
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }
    return result;
}

From source file:com.cinchapi.concourse.util.Convert.java

License:Apache License

/**
 * Convert the next JSON object in the {@code reader} to a mapping that
 * associates each key with the Java objects that represent the
 * corresponding values./*from  w w w. j av  a 2s.  com*/
 * 
 * <p>
 * This method has the same rules and limitations as
 * {@link #jsonToJava(String)}. It simply uses a {@link JsonReader} to
 * handle reading an array of objects.
 * </p>
 * <p>
 * <strong>This method DOES NOT {@link JsonReader#close()} the
 * {@code reader}.</strong>
 * </p>
 * 
 * @param reader the {@link JsonReader} that contains a stream of JSON
 * @return the JSON data in the form of a {@link Multimap} from keys to
 *         values
 */
private static Multimap<String, Object> jsonToJava(JsonReader reader) {
    Multimap<String, Object> data = HashMultimap.create();
    try {
        reader.beginObject();
        JsonToken peek0;
        while ((peek0 = reader.peek()) != JsonToken.END_OBJECT) {
            String key = reader.nextName();
            peek0 = reader.peek();
            if (peek0 == JsonToken.BEGIN_ARRAY) {
                // 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 HashMultimap
                // does not store dupes.
                reader.beginArray();
                JsonToken peek = reader.peek();
                do {
                    Object value;
                    if (peek == JsonToken.BOOLEAN) {
                        value = reader.nextBoolean();
                    } else if (peek == JsonToken.NUMBER) {
                        value = stringToJava(reader.nextString());
                    } else if (peek == JsonToken.STRING) {
                        String orig = reader.nextString();
                        value = stringToJava(orig);
                        if (orig.isEmpty()) {
                            value = orig;
                        }
                        // If the token looks like a string, it MUST be
                        // converted to a Java string unless it is a
                        // masquerading double or an instance of Thrift
                        // translatable class that has a special string
                        // representation (i.e. Tag, Link)
                        else if (orig.charAt(orig.length() - 1) != 'D'
                                && !CLASSES_WITH_ENCODED_STRING_REPR.contains(value.getClass())) {
                            value = value.toString();
                        }
                    } else if (peek == JsonToken.NULL) {
                        reader.skipValue();
                        continue;
                    } else {
                        throw new JsonParseException("Cannot parse nested object or array within an array");
                    }
                    data.put(key, value);
                } while ((peek = reader.peek()) != JsonToken.END_ARRAY);
                reader.endArray();
            } else {
                Object value;
                if (peek0 == JsonToken.BOOLEAN) {
                    value = reader.nextBoolean();
                } else if (peek0 == JsonToken.NUMBER) {
                    value = stringToJava(reader.nextString());
                } else if (peek0 == JsonToken.STRING) {
                    String orig = reader.nextString();
                    value = stringToJava(orig);
                    if (orig.isEmpty()) {
                        value = orig;
                    }
                    // If the token looks like a string, it MUST be
                    // converted to a Java string unless it is a
                    // masquerading double or an instance of Thrift
                    // translatable class that has a special string
                    // representation (i.e. Tag, Link)
                    else if (orig.charAt(orig.length() - 1) != 'D'
                            && !CLASSES_WITH_ENCODED_STRING_REPR.contains(value.getClass())) {
                        value = value.toString();
                    }
                } else if (peek0 == JsonToken.NULL) {
                    reader.skipValue();
                    continue;
                } else {
                    throw new JsonParseException("Cannot parse nested object to value");
                }
                data.put(key, value);
            }
        }
        reader.endObject();
        return data;
    } catch (IOException | IllegalStateException e) {
        throw new JsonParseException(e.getMessage());
    }
}

From source file:com.cloudant.client.api.Database.java

License:Open Source License

/**
 * @param selectorJson//from  w  ww .  j  a  va 2s . com
 * @param sortOrder
 * @param limit
 * @param skip
 * @param returnFields
 * @param readQuorum
 * @return
 */
private String getFindByIndexBody(String selectorJson, FindByIndexOptions options) {

    StringBuilder rf = null;
    if (options.getFields().size() > 0) {
        rf = new StringBuilder("\"fields\": [");
        int i = 0;
        for (String s : options.getFields()) {
            if (i > 0) {
                rf.append(",");
            }
            rf.append("\"").append(s).append("\"");
            i++;
        }
        rf.append("]");
    }

    StringBuilder so = null;
    if (options.getSort().size() > 0) {
        so = new StringBuilder("\"sort\": [");
        int i = 0;
        for (IndexField idxfld : options.getSort()) {
            if (i > 0) {
                so.append(",");
            }
            so.append("{\"").append(idxfld.getName()).append("\": \"").append(idxfld.getOrder()).append("\"}");
            i++;
        }
        so.append("]");
    }

    //parse and find if valid json issue #28
    boolean isObject = true;
    try {
        client.getGson().fromJson(selectorJson, JsonObject.class);
    } catch (JsonParseException e) {
        isObject = false;
    }

    if (!isObject) {
        // needs to start with selector
        if (!(selectorJson.trim().startsWith("\"selector\""))) {
            throw new JsonParseException("selectorJson should be valid json or like " + "\"selector\": {...} ");
        }
    }

    StringBuilder finalbody = new StringBuilder();
    if (isObject) {
        finalbody.append("{\"selector\": ").append(selectorJson);
    } else {
        //old support
        finalbody.append("{" + selectorJson);
    }

    if (rf != null) {
        finalbody.append(",").append(rf.toString());
    }
    if (so != null) {
        finalbody.append(",").append(so.toString());
    }
    if (options.getLimit() != null) {
        finalbody.append(",").append("\"limit\": ").append(options.getLimit());
    }
    if (options.getSkip() != null) {
        finalbody.append(",").append("\"skip\": ").append(options.getSkip());
    }
    if (options.getReadQuorum() != null) {
        finalbody.append(",").append("\"r\": ").append(options.getReadQuorum());
    }
    if (options.getUseIndex() != null) {
        finalbody.append(",").append("\"use_index\": ").append(options.getUseIndex());
    }
    finalbody.append("}");

    return finalbody.toString();
}

From source file:com.cloudant.client.api.DatabaseImpl.java

License:Open Source License

private JsonObject getFindByIndexBody(String selectorJson, FindByIndexOptions options) {

    JsonArray fieldsArray = new JsonArray();
    if (options.getFields().size() > 0) {
        for (String field : options.getFields()) {
            JsonPrimitive jsonField = client.getGson().fromJson(field, JsonPrimitive.class);
            fieldsArray.add(jsonField);//from  ww  w.  j  a  v a2 s  .c o m
        }
    }

    JsonArray sortArray = new JsonArray();
    if (options.getSort().size() > 0) {

        for (IndexField sort : options.getSort()) {
            JsonObject sortObject = new JsonObject();
            sortObject.addProperty(sort.getName(), sort.getOrder().toString());
            sortArray.add(sortObject);
        }
    }

    JsonObject indexObject = new JsonObject();

    //parse and find if valid json issue #28
    JsonObject selectorObject = null;
    boolean isObject = true;
    try {
        selectorObject = getGson().fromJson(selectorJson, JsonObject.class);
    } catch (JsonParseException e) {
        isObject = false;
    }

    if (!isObject) {
        if (selectorJson.startsWith("\"selector\"")) {
            selectorJson = selectorJson.substring(selectorJson.indexOf(":") + 1, selectorJson.length()).trim();
            selectorObject = getGson().fromJson(selectorJson, JsonObject.class);
        } else {
            throw new JsonParseException("selectorJson should be valid json or like " + "\"selector\": {...} ");
        }
    }

    if (selectorObject.has("selector")) {
        indexObject.add("selector", selectorObject.get("selector"));
    } else {
        indexObject.add("selector", selectorObject);
    }

    if (fieldsArray.size() > 0) {
        indexObject.add("fields", fieldsArray);
    }
    if (sortArray.size() > 0) {
        indexObject.add("sort", sortArray);
    }
    if (options.getLimit() != null) {
        indexObject.addProperty("limit", options.getLimit());
    }
    if (options.getSkip() != null) {
        indexObject.addProperty("skip", options.getSkip());
    }
    if (options.getReadQuorum() != null) {
        indexObject.addProperty("r", options.getReadQuorum());
    }
    if (options.getUseIndex() != null) {
        indexObject.add("use_index", getGson().fromJson(options.getUseIndex(), JsonArray.class));
    }

    return indexObject;
}