List of usage examples for com.google.gson JsonElement getAsJsonArray
public JsonArray getAsJsonArray()
From source file:Servlet.java
/** * Handles the HTTP <code>GET</code> method. * * @param request servlet request//w w w. ja v a 2 s . co m * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { Connection connection = null; SQLConnect msql = new SQLConnect(); Gson gson = new Gson(); JsonElement jsonElmnt; JsonArray jsonArr; ArrayList<Alumnos> alumn = new ArrayList<Alumnos>(); connection = msql.conectar(); alumn = msql.getListaAlumn(connection); //Codigo y nombre de los alumnos listados jsonElmnt = gson.toJsonTree(alumn); jsonArr = jsonElmnt.getAsJsonArray(); response.setContentType("application/json"); response.getWriter().print(jsonArr); } catch (SQLException ex) { Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:GeoLocation.java
public static void main(String args[]) { try {/* w ww . j a v a 2s.co m*/ URL myURL = new URL( "https://maps.googleapis.com/maps/api/geocode/json?latlng=17.451425,%2078.380957&key=AIzaSyDe_RBKl4DBGy6YCWRPXi9eQzYACt05Tr8"); URLConnection myURLConnection = myURL.openConnection(); myURLConnection.connect(); BufferedReader in = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = in.readLine()) != null) { sb.append(line + "\n"); } JsonElement json = new JsonParser().parse(sb.toString()); JsonObject j = json.getAsJsonObject(); JsonElement je = j.get("results"); JsonArray ja = je.getAsJsonArray(); JsonElement je1 = ja.get(1); JsonObject j1 = je1.getAsJsonObject(); JsonElement je2 = j1.get("formatted_address"); System.out.println(je2.getAsString()); } catch (MalformedURLException e) { // new URL() failed // ... } catch (IOException e) { // openConnection() failed // ... } }
From source file:EAIJSONConverter.java
License:Open Source License
public static SiebelPropertySet JsonObjectToPropertySet(JsonObject obj, SiebelPropertySet ps) { Iterator<Entry<String, JsonElement>> iterator = obj.entrySet().iterator(); SiebelPropertySet child;/*w w w . j ava 2 s .c o m*/ while (iterator.hasNext()) { JsonArray jsonArray = new JsonArray(); JsonObject jsonObject = new JsonObject(); Map.Entry mapEntry = (Map.Entry) iterator.next(); if (mapEntry != null) { JsonElement jsonelement = (JsonElement) mapEntry.getValue(); if (jsonelement.isJsonArray()) { jsonArray = jsonelement.getAsJsonArray(); child = new SiebelPropertySet(); child.setType("ListOf-" + mapEntry.getKey().toString()); for (int i = 0; i < jsonArray.size(); i++) { if (jsonArray.get(i).isJsonObject() || jsonArray.get(i).isJsonArray()) { SiebelPropertySet temp = new SiebelPropertySet(); temp.setType("" + i); if (jsonArray.get(i).isJsonObject()) child.addChild(JsonObjectToPropertySet(jsonArray.get(i).getAsJsonObject(), temp)); else { JsonObject aux = new JsonObject(); aux.add("" + i, jsonArray.get(i)); child.addChild(JsonObjectToPropertySet(aux, temp)); } } else child.setProperty("" + i, jsonArray.get(i).getAsString()); } ps.addChild(child); } else if (jsonelement.isJsonObject()) { jsonObject = jsonelement.getAsJsonObject(); child = new SiebelPropertySet(); child.setType(mapEntry.getKey().toString()); ps.addChild(JsonObjectToPropertySet(jsonObject, child)); } else { ps.setProperty(mapEntry.getKey().toString(), mapEntry.getValue().toString()); } } } return ps; }
From source file:ambari.interaction.NodeController.java
public static ArrayList<ComponentInformation> getListOfNodes() throws Exception { String url = "http://127.0.0.1:8080/api/v1/clusters/mycluster/services/HDFS/components/DATANODE?fields=host_components/HostRoles/desired_admin_state,host_components/HostRoles/state"; String responseJson = HttpURLConnectionExample.sendGet(url); System.out.print(responseJson); JsonParser jsonParser = new JsonParser(); JsonElement jsonTree = jsonParser.parse(responseJson); ArrayList<ComponentInformation> listOfCompoents = new ArrayList<ComponentInformation>(); if (jsonTree.isJsonObject()) { JsonObject jsonObject = jsonTree.getAsJsonObject(); JsonElement hostComponents = jsonObject.get("host_components"); if (hostComponents.isJsonArray()) { JsonArray hostComponentsJsonArray = hostComponents.getAsJsonArray(); System.out.println("\nStart"); System.out.println(hostComponentsJsonArray); for (int i = 0; i < hostComponentsJsonArray.size(); i++) { JsonElement hostComponentsElem = hostComponentsJsonArray.get(i); if (hostComponentsElem.isJsonObject()) { JsonObject jsonObjectElem = hostComponentsElem.getAsJsonObject(); JsonElement hostRolesElem = jsonObjectElem.get("HostRoles"); if (hostRolesElem.isJsonObject()) { JsonObject hostRolesObjs = hostRolesElem.getAsJsonObject(); JsonElement componentNameElem = hostRolesObjs.get("component_name"); JsonElement hostNameElem = hostRolesObjs.get("host_name"); JsonElement stateElem = hostRolesObjs.get("state"); listOfCompoents.add(new ComponentInformation(componentNameElem.toString(), hostNameElem.toString(), stateElem.toString())); }/*w ww. j a v a 2s . c om*/ } } } } return listOfCompoents; }
From source file:angularBeans.remote.InvocationHandler.java
License:LGPL
private void genericInvoke(Object service, String methodName, JsonObject params, Map<String, Object> returns, long reqID, String UID, HttpServletRequest request) throws SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { Object mainReturn = null;/*from w ww . ja v a2 s . com*/ Method m = null; JsonElement argsElem = params.get("args"); if (reqID > 0) { returns.put("reqId", reqID); } if (argsElem != null) { JsonArray args = params.get("args").getAsJsonArray(); for (Method mt : service.getClass().getMethods()) { if (mt.getName().equals(methodName)) { m = mt; Type[] parameters = mt.getParameterTypes(); if (parameters.length == args.size()) { List<Object> argsValues = new ArrayList<>(); for (int i = 0; i < parameters.length; i++) { Class typeClass; String typeString = ((parameters[i]).toString()); if (typeString.startsWith("interface")) { typeString = typeString.substring(10); typeClass = Class.forName(typeString); } else { if (typeString.startsWith("class")) { typeString = typeString.substring(6); typeClass = Class.forName(typeString); } else { typeClass = builtInMap.get(typeString); } } JsonElement element = args.get(i); if (element.isJsonPrimitive()) { String val = element.getAsString(); argsValues.add(CommonUtils.convertFromString(val, typeClass)); } else if (element.isJsonArray()) { JsonArray arr = element.getAsJsonArray(); argsValues.add(util.deserialise(arrayTypesMap.get(typeString), arr)); } else { argsValues.add(util.deserialise(typeClass, element)); } } if (!CommonUtils.isGetter(mt)) { update(service, params); } try { mainReturn = mt.invoke(service, argsValues.toArray()); } catch (Exception e) { handleException(mt, e); e.printStackTrace(); } } } } } else { for (Method mt : service.getClass().getMethods()) { if (mt.getName().equals(methodName)) { Type[] parameters = mt.getParameterTypes(); // handling methods that took HttpServletRequest as parameter if (parameters.length == 1) { // if(mt.getParameters()[0].getType()==HttpServletRequest.class) // { // System.out.println("hehe..."); // mt.invoke(service, request); // // } } else { if (!CommonUtils.isGetter(m)) { update(service, params); } mainReturn = mt.invoke(service); } } } } ModelQueryImpl qImpl = (ModelQueryImpl) modelQueryFactory.get(service.getClass()); Map<String, Object> scMap = new HashMap<>(qImpl.getData()); returns.putAll(scMap); qImpl.getData().clear(); if (!modelQueryFactory.getRootScope().getRootScopeMap().isEmpty()) { returns.put("rootScope", new HashMap<>(modelQueryFactory.getRootScope().getRootScopeMap())); modelQueryFactory.getRootScope().getRootScopeMap().clear(); } String[] updates = null; if (m.isAnnotationPresent(NGReturn.class)) { if (mainReturn == null) mainReturn = ""; NGReturn ngReturn = m.getAnnotation(NGReturn.class); updates = ngReturn.updates(); if (ngReturn.model().length() > 0) { returns.put(ngReturn.model(), mainReturn); Map<String, String> binding = new HashMap<>(); binding.put("boundTo", ngReturn.model()); mainReturn = binding; } } if (m.isAnnotationPresent(NGPostConstruct.class)) { NGPostConstruct ngPostConstruct = m.getAnnotation(NGPostConstruct.class); updates = ngPostConstruct.updates(); } if (updates != null) { if ((updates.length == 1) && (updates[0].equals("*"))) { List<String> upd = new ArrayList<>(); for (Method met : service.getClass().getDeclaredMethods()) { if (CommonUtils.isGetter(met)) { String fieldName = (met.getName()).substring(3); String firstCar = fieldName.substring(0, 1); upd.add((firstCar.toLowerCase() + fieldName.substring(1))); } } updates = new String[upd.size()]; for (int i = 0; i < upd.size(); i++) { updates[i] = upd.get(i); } } } if (updates != null) { for (String up : updates) { String getterName = GETTER_PREFIX + up.substring(0, 1).toUpperCase() + up.substring(1); Method getter; try { getter = service.getClass().getMethod(getterName); } catch (NoSuchMethodException e) { getter = service.getClass() .getMethod((getterName.replace(GETTER_PREFIX, BOOLEAN_GETTER_PREFIX))); } Object result = getter.invoke(service); returns.put(up, result); } } returns.put("mainReturn", mainReturn); if (!logger.getLogPool().isEmpty()) { returns.put("log", logger.getLogPool().toArray()); logger.getLogPool().clear(); } }
From source file:angularBeans.remote.InvocationHandler.java
License:LGPL
private void update(Object o, JsonObject params) { if (params != null) { // boolean firstIn = false; for (Map.Entry<String, JsonElement> entry : params.entrySet()) { JsonElement value = entry.getValue(); String name = entry.getKey(); if ((name.equals("sessionUID")) || (name.equals("args"))) { continue; }/*from w w w. j ava 2 s . c o m*/ if ((value.isJsonObject()) && (!value.isJsonNull())) { String getName; try { getName = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name)); Method getter = o.getClass().getMethod(getName); Object subObj = getter.invoke(o); // logger.log(Level.INFO, "#entring sub object "+name); update(subObj, value.getAsJsonObject()); } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } } // ------------------------------------ if (value.isJsonArray()) { try { String getter = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name)); Method get = o.getClass().getDeclaredMethod(getter); Type type = get.getGenericReturnType(); ParameterizedType pt = (ParameterizedType) type; Type actType = pt.getActualTypeArguments()[0]; String className = actType.toString(); className = className.substring(className.indexOf("class") + 6); Class clazz = Class.forName(className); JsonArray array = value.getAsJsonArray(); Collection collection = (Collection) get.invoke(o); Object elem; for (JsonElement element : array) { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); elem = element; if (primitive.isBoolean()) elem = primitive.getAsBoolean(); if (primitive.isString()) { elem = primitive.getAsString(); } if (primitive.isNumber()) elem = primitive.isNumber(); } else { elem = util.deserialise(clazz, element); } try { if (collection instanceof List) { if (collection.contains(elem)) collection.remove(elem); } collection.add(elem); } catch (UnsupportedOperationException e) { Logger.getLogger("AngularBeans").log(java.util.logging.Level.WARNING, "trying to modify an immutable collection : " + name); } } } catch (Exception e) { e.printStackTrace(); } } // ------------------------------------------ if (value.isJsonPrimitive() && (!name.equals("setSessionUID"))) { try { if (!CommonUtils.hasSetter(o.getClass(), name)) { continue; } name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Class type = null; for (Method set : o.getClass().getDeclaredMethods()) { if (CommonUtils.isSetter(set)) { if (set.getName().equals(name)) { Class<?>[] pType = set.getParameterTypes(); type = pType[0]; break; } } } if (type.equals(LobWrapper.class)) continue; Object param = null; if ((params.entrySet().size() >= 1) && (type != null)) { param = CommonUtils.convertFromString(value.getAsString(), type); } o.getClass().getMethod(name, type).invoke(o, param); } catch (Exception e) { e.printStackTrace(); } } } } }
From source file:ar.com.mapfre.ejemploajaxjsonarray.ServletCargarTabla.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ArrayList<Paises> pais = new ArrayList<>(); pais = ObtenerDatos.getAllCountries(); Gson gson = new Gson(); JsonElement element = gson.toJsonTree(pais, new TypeToken<List<Paises>>() { }.getType());// ww w . j a va2 s . c o m JsonArray jsonArray = element.getAsJsonArray(); response.setContentType("application/json"); response.getWriter().print(jsonArray); }
From source file:arces.unibo.SEPA.commons.SPARQL.BindingsResults.java
License:Open Source License
private JsonArray getBindingsArray() { JsonElement varArray; if (results == null) return null; if ((varArray = results.get("results")) == null) return null; if ((varArray = varArray.getAsJsonObject().get("bindings")) == null) return null; return varArray.getAsJsonArray(); }
From source file:arces.unibo.SEPA.commons.SPARQL.BindingsResults.java
License:Open Source License
private JsonArray getVariablesArray() { JsonElement varArray; if (results == null) return null; if ((varArray = results.get("head")) == null) return null; if ((varArray = varArray.getAsJsonObject().get("vars")) == null) return null; return varArray.getAsJsonArray(); }
From source file:at.maui.cheapcast.json.deserializer.ProtocolMessageDeserializer.java
License:Apache License
@Override public ProtocolMessage deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { ProtocolMessage pm;/*from w ww.ja v a 2s . co m*/ if (jsonElement.isJsonArray()) { JsonArray arr = jsonElement.getAsJsonArray(); pm = new ProtocolMessage(); pm.setProtocol(arr.get(0).getAsString()); if (pm.getProtocol().equals("ramp")) { pm.setPayload((RampMessage) jsonDeserializationContext.deserialize(arr.get(1), RampMessage.class)); } else if (pm.getProtocol().equals("cm")) { pm.setPayload((CmMessage) jsonDeserializationContext.deserialize(arr.get(1), CmMessage.class)); } return pm; } return null; //To change body of implemented methods use File | Settings | File Templates. }