List of usage examples for com.google.gson JsonParseException JsonParseException
public JsonParseException(Throwable cause)
From source file:com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput.java
License:Open Source License
public JsonArray fetchArray(InputJsonKeys.VendorAPISource.MainTypes entityType, int page) throws IOException { HashMap<String, String> params = null; if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics) || entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.speakers)) { params = new HashMap<String, String>(); // Topics and speakers require param "includeinfo=true" to bring extra data params.put("includeinfo", "true"); if (entityType.equals(InputJsonKeys.VendorAPISource.MainTypes.topics)) { if (extractUnpublished) { params.put("minpublishstatus", "0"); }//w w w . j a va 2 s . c o m } } if (page == 0) { page = 1; } else if (page > 1) { if (params == null) { params = new HashMap<String, String>(); } params.put("page", Integer.toString(page)); } JsonElement element = getFetcher().fetch(entityType, params); if (element.isJsonArray()) { return element.getAsJsonArray(); } else if (element.isJsonObject()) { // check if there are extra pages requiring further fetching JsonObject obj = element.getAsJsonObject(); checkPagingConsistency(entityType, page, obj); int pageSize = obj.get("pagesize").getAsInt(); int totalEntities = obj.get("total").getAsInt(); JsonArray elements = getEntities(obj); if (page * pageSize < totalEntities) { // fetch the next page elements.addAll(fetchArray(entityType, page + 1)); } return elements; } else { throw new JsonParseException("Invalid response from Vendor API. Request should return " + "either a JsonArray or a JsonObject, but returned " + element.getClass().getName() + ". Entity fetcher is " + getFetcher()); } }
From source file:com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput.java
License:Open Source License
private void checkPagingConsistency(InputJsonKeys.VendorAPISource.MainTypes entityType, int requestedPage, JsonObject obj) {/*from w w w . ja va2s . c om*/ if (!obj.has("page") || !obj.has("pagesize") || !obj.has("total") || (!obj.has("results") && !obj.has("topics"))) { throw new JsonParseException("Invalid response from Vendor API when" + "paging " + entityType + " results. At least one of the required properties " + "(page, pagesize, total, results|topics) could not be found."); } int currentPage = obj.get("page").getAsInt(); if (requestedPage > 0 && requestedPage != currentPage) { throw new JsonParseException("Invalid response from Vendor API when" + "paging " + entityType + " results. Requested page " + requestedPage + " but got page " + currentPage); } }
From source file:com.google.samples.apps.iosched.server.schedule.server.input.VendorDynamicInput.java
License:Open Source License
private JsonArray getEntities(JsonObject pagedObject) { JsonArray elements;// w w w . j a v a2 s .c o m if (pagedObject.has("results")) { elements = pagedObject.get("results").getAsJsonArray(); } else if (pagedObject.has("topics")) { elements = pagedObject.get("topics").getAsJsonArray(); } else { throw new JsonParseException( "Invalid JSON format for a paged result. Expected either a \"results\" or a topics array property."); } return elements; }
From source file:com.google.wave.api.impl.EventMessageBundleGsonAdaptor.java
License:Apache License
@Override public JsonElement serialize(EventMessageBundle src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); JsonArray events = new JsonArray(); for (Event event : src.getEvents()) { try {// w w w . j a va 2 s . c o m events.add(EventSerializer.serialize(event, context)); } catch (EventSerializationException e) { throw new JsonParseException(e); } } result.add(EVENTS_TAG, events); result.add(WAVELET_TAG, context.serialize(src.getWaveletData())); result.add(BLIPS_TAG, context.serialize(src.getBlipData())); result.add(THREADS_TAG, context.serialize(src.getThreads())); result.addProperty(ROBOT_ADDRESS_TAG, src.getRobotAddress()); String proxyingFor = src.getProxyingFor(); if (proxyingFor != null && !proxyingFor.isEmpty()) { result.addProperty(PROXYING_FOR_TAG, proxyingFor); } String rpcServerUrl = src.getRpcServerUrl(); if (rpcServerUrl != null && !rpcServerUrl.isEmpty()) { result.addProperty(RPC_SERVER_URL_TAG, rpcServerUrl); } return result; }
From source file:com.google.wave.api.impl.EventMessageBundleGsonAdaptor.java
License:Apache License
@Override public EventMessageBundle deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObj = json.getAsJsonObject(); String robotAddress = jsonObj.get(ROBOT_ADDRESS_TAG).getAsString(); String rpcServerUrl = ""; if (jsonObj.has(RPC_SERVER_URL_TAG)) { rpcServerUrl = jsonObj.get(RPC_SERVER_URL_TAG).getAsString(); }/* w ww . ja va 2 s . com*/ EventMessageBundle result = new EventMessageBundle(robotAddress, rpcServerUrl); OperationQueue operationQueue; if (jsonObj.has(PROXYING_FOR_TAG)) { result.setProxyingFor(jsonObj.get(PROXYING_FOR_TAG).getAsString()); operationQueue = new OperationQueue(new ArrayList<OperationRequest>(), result.getProxyingFor()); } else { operationQueue = new OperationQueue(); } // Deserialize wavelet. WaveletData waveletData = context.deserialize(jsonObj.get(WAVELET_TAG), WaveletData.class); result.setWaveletData(waveletData); Map<String, Blip> blips = new HashMap<String, Blip>(); Map<String, BlipThread> threads = new HashMap<String, BlipThread>(); Wavelet wavelet = Wavelet.deserialize(operationQueue, blips, threads, waveletData); wavelet.setRobotAddress(robotAddress); result.setWavelet(wavelet); // Deserialize threads. Map<String, BlipThread> tempThreads = context.deserialize(jsonObj.get(THREADS_TAG), GsonFactory.THREAD_MAP_TYPE); for (Entry<String, BlipThread> entry : tempThreads.entrySet()) { BlipThread thread = entry.getValue(); threads.put(entry.getKey(), new BlipThread(thread.getId(), thread.getLocation(), thread.getBlipIds(), blips)); } // Deserialize blips. Map<String, BlipData> blipDatas = context.deserialize(jsonObj.get(BLIPS_TAG), GsonFactory.BLIP_MAP_TYPE); result.setBlipData(blipDatas); for (Entry<String, BlipData> entry : blipDatas.entrySet()) { blips.put(entry.getKey(), Blip.deserialize(operationQueue, wavelet, entry.getValue())); } // Deserialize events. JsonArray eventsArray = jsonObj.get(EVENTS_TAG).getAsJsonArray(); List<Event> events = new ArrayList<Event>(eventsArray.size()); for (JsonElement element : eventsArray) { JsonObject eventObject = element.getAsJsonObject(); try { events.add(EventSerializer.deserialize(wavelet, result, eventObject, context)); } catch (EventSerializationException e) { throw new JsonParseException(e.getMessage()); } } result.setEvents(events); return result; }
From source file:com.graphhopper.json.FeatureJsonDeserializer.java
License:Apache License
@Override public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { try {//from w w w. j a v a 2 s .c o m JsonObject obj = json.getAsJsonObject(); String id, strType = null; Map<String, Object> properties = null; BBox bbox = null; Geometry geometry = null; // TODO ensure uniqueness if (obj.has("id")) id = obj.get("id").getAsString(); else id = UUID.randomUUID().toString(); if (obj.has("properties")) { properties = context.deserialize(obj.get("properties"), Map.class); } if (obj.has("bbox")) bbox = parseBBox(obj.get("bbox").getAsJsonArray()); if (obj.has("geometry")) { JsonObject geometryJson = obj.get("geometry").getAsJsonObject(); if (geometryJson.has("coordinates")) { if (!geometryJson.has("type")) throw new IllegalArgumentException("No type for non-empty coordinates specified"); strType = context.deserialize(geometryJson.get("type"), String.class); if ("Point".equals(strType)) { JsonArray arr = geometryJson.get("coordinates").getAsJsonArray(); double lon = arr.get(0).getAsDouble(); double lat = arr.get(1).getAsDouble(); if (arr.size() == 3) geometry = new Point(lat, lon, arr.get(2).getAsDouble()); else geometry = new Point(lat, lon); } else if ("MultiPoint".equals(strType)) { geometry = parseLineString(geometryJson); } else if ("LineString".equals(strType)) { geometry = parseLineString(geometryJson); } else { throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported"); } } } return new JsonFeature(id, strType, bbox, geometry, properties); } catch (Exception ex) { throw new JsonParseException("Problem parsing JSON feature " + json); } }
From source file:com.graphhopper.json.geo.FeatureJsonDeserializer.java
License:Apache License
@Override public JsonFeature deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { try {/*from w w w . jav a2 s.co m*/ JsonFeature feature = new JsonFeature(); JsonObject obj = json.getAsJsonObject(); // TODO ensure uniqueness if (obj.has("id")) feature.id = obj.get("id").getAsString(); else feature.id = UUID.randomUUID().toString(); if (obj.has("properties")) { Map<String, Object> map = context.deserialize(obj.get("properties"), Map.class); feature.properties = map; } if (obj.has("bbox")) feature.bbox = parseBBox(obj.get("bbox").getAsJsonArray()); if (obj.has("geometry")) { JsonObject geometry = obj.get("geometry").getAsJsonObject(); if (geometry.has("coordinates")) { if (!geometry.has("type")) throw new IllegalArgumentException("No type for non-empty coordinates specified"); String strType = context.deserialize(geometry.get("type"), String.class); feature.type = strType; if ("Point".equals(strType)) { JsonArray arr = geometry.get("coordinates").getAsJsonArray(); double lon = arr.get(0).getAsDouble(); double lat = arr.get(1).getAsDouble(); if (arr.size() == 3) feature.geometry = new Point(lat, lon, arr.get(2).getAsDouble()); else feature.geometry = new Point(lat, lon); } else if ("MultiPoint".equals(strType)) { feature.geometry = parseLineString(geometry); } else if ("LineString".equals(strType)) { feature.geometry = parseLineString(geometry); } else { throw new IllegalArgumentException("Coordinates type " + strType + " not yet supported"); } } } return feature; } catch (Exception ex) { throw new JsonParseException("Problem parsing JSON feature " + json); } }
From source file:com.gsaul.AethonSimulator.RuntimeTypeAdapterFactory.java
License:Apache License
public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) { if (type.getRawType() != baseType) { return null; }//from w w w. jav a2 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().get(typeFieldName); //used to be .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.hagreve.android.lib.HaGreveApi.java
License:Apache License
/** * Obtains the list of current strikes./*from w ww. j a v a2s .c o m*/ * @return Array of Strike objects */ public static Strike[] getStrikes() { Strike[] items = new Strike[0]; String result = doGetRequest(BASE_URL + "/strikes"); if (result != null) { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); try { return formatter.parse(json.getAsString()); } catch (ParseException e) { throw new JsonParseException(e.getMessage()); } } }); Gson gson = builder.create(); items = gson.fromJson(result, Strike[].class); } return items; }
From source file:com.heartbuffer.pipette.json.FilterConfigJsonAdapter.java
License:Open Source License
@Override public FilterConfig deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonPrimitive primitive = (JsonPrimitive) jsonObject.get(TYPE_FIELD); String filterType = primitive.getAsString(); Class<?> clazz = null;/* ww w .j av a 2 s .c o m*/ switch (filterType) { case AddTimestampFilter.TYPE: clazz = AddTimestampFilterConfig.class; break; case EsDetermineDocumentDataFilter.TYPE: clazz = EsDetermineDocumentDataFilterConfig.class; break; case NDiffFilter.TYPE: //TODO: Add NDiffFilterConfig break; default: throw new JsonParseException("No such filter of type '" + filterType + "'"); } return context.deserialize(jsonObject, clazz); }