List of usage examples for com.google.gson JsonElement getAsJsonArray
public JsonArray getAsJsonArray()
From source file:com.mediamath.terminalone.service.GetService.java
License:Apache License
/** * parses error response of Get operation. * // w ww. jav a 2 s . co m * @param responseStr * string. * @return JsonPostErrorResponse object. */ public JsonPostErrorResponse jsonGetErrorResponseParser(String responseStr) { JsonParser parser1 = new JsonParser(); JsonObject obj = parser1.parse(responseStr).getAsJsonObject(); JsonElement errorsElement = obj.get("errors"); JsonElement errorElement = obj.get("error"); JsonElement metaElement = obj.get("meta"); JsonPostErrorResponse errorResponse = null; if (errorsElement != null || errorElement != null) { errorResponse = new JsonPostErrorResponse(); GsonBuilder builder = new GsonBuilder(); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS); Gson gson = builder.create(); if (errorsElement != null) { if (errorsElement.isJsonNull()) { } else if (errorsElement.isJsonObject()) { T1Error errors = gson.fromJson(errorsElement, T1Error.class); // specific to video creatives if (errors != null && errors.getContent() == null && errors.getField() == null && errors.getFieldError() == null && errors.getMessage() == null) { GsonBuilder videoBuilder = new GsonBuilder(); videoBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); videoBuilder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS); Gson vidgson = videoBuilder.create(); errors = vidgson.fromJson(errorsElement, T1Error.class); } errorResponse.setErrors(errors); } else if (errorsElement.isJsonArray()) { JsonArray array = errorsElement.getAsJsonArray(); JsonArray newArray = new JsonArray(); for (int i = 0; i < array.size(); i++) { if (!(array.get(i) instanceof JsonPrimitive)) { newArray.add(array.get(i)); } } if (newArray.size() > 0) { errorsElement = newArray; Type type = new TypeToken<ArrayList<T1Error>>() { }.getType(); List<T1Error> errors = gson.fromJson(errorsElement, type); errorResponse.setErrors(errors); } } } if (errorElement != null) { T1Error error = gson.fromJson(errorElement, T1Error.class); errorResponse.setError(error); } if (metaElement != null) { T1Meta meta = gson.fromJson(metaElement, T1Meta.class); errorResponse.setMeta(meta); } } return errorResponse; }
From source file:com.mediamath.terminalone.service.PostService.java
License:Apache License
/** * parses error response of a POST activity. * //from w w w . j a v a 2s . co m * @param responseStr * requires a response JSON string * @param responseObj * requires a Response object. * @return JsonPostErrorResponse entity. */ public JsonPostErrorResponse jsonPostErrorResponseParser(String responseStr, Response responseObj) { JsonParser parser1 = new JsonParser(); JsonObject obj = parser1.parse(responseStr).getAsJsonObject(); JsonElement errorsElement = obj.get("errors"); JsonElement errorElement = obj.get("error"); JsonElement metaElement = obj.get("meta"); JsonPostErrorResponse errorResponse = null; if (errorsElement != null || errorElement != null || (responseObj != null && responseObj.getStatus() == 403 && metaElement != null)) { errorResponse = new JsonPostErrorResponse(); GsonBuilder builder = new GsonBuilder(); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS); Gson gson = builder.create(); if (errorsElement != null) { if (errorsElement.isJsonObject()) { T1Error errors = gson.fromJson(errorsElement, T1Error.class); // specific to video creatives if (errors != null && errors.getContent() == null && errors.getField() == null && errors.getFieldError() == null && errors.getMessage() == null) { GsonBuilder videoBuilder = new GsonBuilder(); videoBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); videoBuilder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS); Gson vidgson = videoBuilder.create(); errors = vidgson.fromJson(errorsElement, T1Error.class); } errorResponse.setErrors(errors); } else if (errorsElement.isJsonArray()) { JsonArray array = errorsElement.getAsJsonArray(); JsonArray newArray = new JsonArray(); for (int i = 0; i < array.size(); i++) { if (!(array.get(i) instanceof JsonPrimitive)) { newArray.add(array.get(i)); } } if (newArray.size() > 0) { errorsElement = newArray; Type type = new TypeToken<ArrayList<T1Error>>() { }.getType(); List<T1Error> errors = gson.fromJson(errorsElement, type); errorResponse.setErrors(errors); } } } if (errorElement != null) { T1Error error = gson.fromJson(errorElement, T1Error.class); errorResponse.setError(error); } if (metaElement != null) { if (responseObj != null && responseObj.getStatus() == 403) { T1Meta meta = gson.fromJson(metaElement, T1Meta.class); errorResponse.setMeta(meta); } } } return errorResponse; }
From source file:com.mediamath.terminalone.service.PostService.java
License:Apache License
private <T extends T1Entity> JsonResponse<? extends T1Entity> parsePostData(String response, T1JsonToObjParser parser, T entity) throws ParseException { // parse the string to gson objs JsonResponse<? extends T1Entity> finalJsonResponse = null; JsonElement element = parser.getDataFromResponse(response); if (element != null) { if (element.isJsonArray()) { // do something JsonArray dataList = element.getAsJsonArray(); String entityType;//from w ww . j av a 2 s . co m if (dataList.size() > 0) { JsonElement data = dataList.get(0); if (data != null) { JsonObject dataObj = data.getAsJsonObject(); if (dataObj != null) { JsonElement entityTypeElem = dataObj.get("entity_type"); if (entityTypeElem != null) { entityType = entityTypeElem.getAsString(); if (entityType != null && !entityType.isEmpty()) { if (Constants.getListoFEntityType.get(entityType) != null) { finalJsonResponse = parser.parseJsonToObj(response, Constants.getListoFEntityType.get(entityType)); } } } } } } } else if (element.isJsonObject()) { JsonObject obj = element.getAsJsonObject(); JsonElement entityTypeElement = obj.get("entity_type"); String entityType = entityTypeElement.getAsString(); finalJsonResponse = parser.parseJsonToObj(response, Constants.getEntityType.get(entityType)); } } else if (element == null) { if (entity != null) { finalJsonResponse = parser.parseJsonToObj(response, Constants.getEntityType.get(entity.getEntityname().toLowerCase())); if (finalJsonResponse != null) { finalJsonResponse.setData(null); } } } return finalJsonResponse; }
From source file:com.mediamath.terminalone.TerminalOne.java
License:Apache License
/** * parses the response to objects.//from w w w . ja va2 s . c o m * * @param response * a valid JSON response string is required. * @param QueryCriteria * a valid query object is required. * @return JsonResponse<? extends T1Entity> JsonResponse of type T is returned. * @throws ClientException * a client exception is thrown if any error occurs. * @throws ParseException * a parse exception is thrown when the response cannot be parsed. */ private <T extends T1Entity> JsonResponse<? extends T1Entity> parseGetData(String response, QueryCriteria query) throws ParseException, ClientException { T1JsonToObjParser parser = new T1JsonToObjParser(); // parse the string to gson objs JsonResponse<? extends T1Entity> finalJsonResponse = null; JsonPostErrorResponse jsonPostErrorResponse = null; // check whether error present jsonPostErrorResponse = getService.jsonGetErrorResponseParser(response); // if no error if (jsonPostErrorResponse == null) { JsonElement element = parser.getDataFromResponse(response); if (element != null) { if (element.isJsonArray()) { // do something JsonArray dataList = element.getAsJsonArray(); String entityType; if (dataList.size() > 0) { JsonElement data = dataList.get(0); if (data != null) { JsonObject dataObj = data.getAsJsonObject(); if (dataObj != null) { JsonElement entityTypeElem = dataObj.get("entity_type"); if (entityTypeElem != null) { entityType = entityTypeElem.getAsString(); if (entityType != null && !entityType.isEmpty()) { if (Constants.getListoFEntityType.get(entityType) != null) { finalJsonResponse = parser.parseJsonToObj(response, Constants.getListoFEntityType.get(entityType)); } } } } } } else { if (query.collection != null) { finalJsonResponse = parser.parseJsonToObj(response, Constants.getListoFEntityType.get(query.collection.toLowerCase())); } } } else if (element.isJsonObject()) { JsonObject obj = element.getAsJsonObject(); JsonElement entityTypeElement = obj.get("entity_type"); String entityType = (entityTypeElement != null) ? entityTypeElement.getAsString() : null; if (entityType != null && !entityType.equalsIgnoreCase("")) { finalJsonResponse = parser.parseJsonToObj(response, Constants.getEntityType.get(entityType)); } else { finalJsonResponse = parser.parseJsonToObj(response, new TypeToken<JsonResponse<Data>>() { }.getType()); } } } else if (element == null) { if (query.collection != null) { finalJsonResponse = parser.parseJsonToObj(response, Constants.getEntityType.get(query.collection.toLowerCase())); if (finalJsonResponse != null) { finalJsonResponse.setData(null); } } } } else { postService.throwExceptions(jsonPostErrorResponse); } return finalJsonResponse; }
From source file:com.mesos.framework.impl.MesosMonitor.java
License:Apache License
/** * a sample return//ww w . j av a2s . c o m * [{"executor_id":"task-acmeair.9bd310f1-b009-4b26-8074-864d3420988a","executor_name":"Command Executor (Task: task-acmeair.9bd310f1-b009-4b26-8074-864d3420988a) (Command: NO EXECUTABLE)","framework_id":"7a233ad6-e506-42dd-a9ff-a9821d93d3e3-0089","source":"task-acmeair.9bd310f1-b009-4b26-8074-864d3420988a","statistics":{"cpus_limit":1.1,"cpus_system_time_secs":0.1,"cpus_user_time_secs":0.45,"mem_limit_bytes":1107296256,"mem_rss_bytes":26841088,"timestamp":1458334777.05838}}] * @param host * @return */ private JsonArray getStatistics(String host) { try { String sURL = "http://" + host + ":5051/monitor/statistics.json"; URL url = new URL(sURL); HttpURLConnection request = (HttpURLConnection) url.openConnection(); request.connect(); JsonParser jp = new JsonParser(); JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); return root.getAsJsonArray(); } catch (Exception e) { logger.error(e.getMessage()); } return null; }
From source file:com.microsoft.windowsazure.mobileservices.MobileServiceTable.java
License:Open Source License
/** * Parses the JSON object to a typed list * /*from w w w . j a va 2s . com*/ * @param results * JSON results * @return List of entities */ private List<E> parseResults(JsonElement results) { Gson gson = mClient.getGsonBuilder().create(); List<E> result = new ArrayList<E>(); String idPropertyName = getIdPropertyName(mClazz); // Parse results if (results.isJsonArray()) // Query result { JsonArray elements = results.getAsJsonArray(); for (JsonElement element : elements) { changeIdPropertyName(element.getAsJsonObject(), idPropertyName); E typedElement = gson.fromJson(element, mClazz); result.add(typedElement); } } else { // Lookup result changeIdPropertyName(results.getAsJsonObject(), idPropertyName); E typedElement = gson.fromJson(results, mClazz); result.add(typedElement); } return result; }
From source file:com.microsoft.windowsazure.mobileservices.table.serialization.JsonEntityParser.java
License:Open Source License
/** * Parses the JSON object to a typed list * * @param results JSON results//from w w w . jav a 2 s .com * @param gson Gson object used for parsing * @param clazz Target entity class * @return List of entities */ public static <E> List<E> parseResults(JsonElement results, Gson gson, Class<E> clazz) { List<E> result = new ArrayList<E>(); String idPropertyName = getIdPropertyName(clazz); // Parse results if (results.isJsonArray()) { // Query result JsonArray elements = results.getAsJsonArray(); for (JsonElement element : elements) { changeIdPropertyName(element.getAsJsonObject(), idPropertyName); E typedElement = gson.fromJson(element, clazz); result.add(typedElement); } } else { // Lookup result if (results.isJsonObject()) { changeIdPropertyName(results.getAsJsonObject(), idPropertyName); } E typedElement = gson.fromJson(results, clazz); result.add(typedElement); } return result; }
From source file:com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext.java
License:Open Source License
private void processPull(String tableName, Query query, String queryId) throws Throwable { try {/*from w ww .j av a 2 s. com*/ MobileServiceJsonTable table = this.mClient.getTable(tableName); table.addFeature(MobileServiceFeatures.Offline); if (query == null) { query = table.top(1000).orderBy("id", QueryOrder.Ascending); } else { query = query.deepClone(); } PullStrategy strategy; if (queryId != null) { strategy = new IncrementalPullStrategy(query, queryId, this.mStore, table); } else { strategy = new PullStrategy(query, table); } strategy.initialize(); JsonArray elements = null; do { JsonElement result = table.execute(strategy.getLastQuery()).get(); if (result != null) { if (result.isJsonObject()) { JsonObject jsonObject = result.getAsJsonObject(); if (jsonObject.has("results") && jsonObject.get("results").isJsonArray()) { elements = jsonObject.get("results").getAsJsonArray(); } } else if (result.isJsonArray()) { elements = result.getAsJsonArray(); } processElements(tableName, elements); strategy.onResultsProcessed(elements); } } while (strategy.moveToNextPage(elements.size())); } catch (ExecutionException e) { throw e.getCause(); } catch (RuntimeException e) { throw e.getCause(); } }
From source file:com.miko.s4netty.handler.WorkerProviderHandler.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { if (msg instanceof HttpRequest) { HttpRequest req = (HttpRequest) msg; if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); }//from w w w . j av a 2 s . c om boolean keepAlive = isKeepAlive(req); logger.debug("channelRead keepAlive= " + keepAlive); Gson gson = new Gson(); List<CarDTO> carList = simpleCarService.getAll(); Map<String, List<CarDTO>> byMake = simpleCarService.getAll().stream() .collect(Collectors.groupingBy(CarDTO::getMake)); System.out.println("byMake = " + byMake); System.out.println("byMake Skoda= " + byMake.get("Skoda").iterator().next().getModel()); JsonElement element = gson.toJsonTree(carList, new TypeToken<List<CarDTO>>() { }.getType()); JsonArray jsonArray = element.getAsJsonArray(); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(jsonArray.toString().getBytes())); response.headers().set(CONTENT_TYPE, "application/json"); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); //ignoring KeepAlive ctx.write(response).addListener(ChannelFutureListener.CLOSE); } }
From source file:com.money.manager.ex.investment.yql.YqlSecurityPriceUpdaterRetrofit.java
License:Open Source License
private List<SecurityPriceModel> getPricesFromJson(JsonObject root) { ArrayList<SecurityPriceModel> result = new ArrayList<>(); // check whether there is only one item or more JsonElement results = root.get("query").getAsJsonObject().get("results"); if (results == null) return null; JsonObject resultsJson = results.getAsJsonObject(); if (resultsJson == null) return null; JsonElement quoteElement = resultsJson.get("quote"); if (quoteElement instanceof JsonArray) { JsonArray quotes = quoteElement.getAsJsonArray(); for (int i = 0; i < quotes.size(); i++) { JsonObject quote = quotes.get(i).getAsJsonObject(); // process individual quote SecurityPriceModel priceModel = getSecurityPriceFor(quote); if (priceModel == null) continue; result.add(priceModel);/* w w w . ja v a2 s. c o m*/ } } else { // Single quote JsonObject quote = quoteElement.getAsJsonObject(); SecurityPriceModel priceModel = getSecurityPriceFor(quote); if (priceModel != null) { result.add(priceModel); } } return result; }