List of usage examples for com.google.gson JsonElement isJsonObject
public boolean isJsonObject()
From source file:com.cybozu.kintone.database.JsonParser.java
License:Apache License
/** * Reads and parses each comment element. * @param elem/*www .jav a 2s. com*/ * a json element represents a comment object * @return the comment object created * @throws IOException */ private Comment readComment(JsonElement elem) throws IOException { Comment comment = null; Gson gson = new Gson(); if (elem.isJsonObject()) { JsonObject obj = elem.getAsJsonObject(); long id = obj.get("id").getAsLong(); String text = obj.get("text").getAsString(); Date createdAt = getDateTime(obj.get("createdAt").getAsString()); Type userElementType = new TypeToken<UserDto>() { }.getType(); UserDto user = gson.fromJson(obj.getAsJsonObject("creator"), userElementType); Type mentionsElementType = new TypeToken<Collection<MentionDto>>() { }.getType(); List<MentionDto> mentions = gson.fromJson(obj.getAsJsonArray("mentions"), mentionsElementType); comment = new Comment(id, text, createdAt, user, mentions); } return comment; }
From source file:com.dell.prototype.apm.server.AppServerMonitorDataSubmissionServlet.java
License:Open Source License
@Override public void doPost(HttpServletRequest request, HttpServletResponse response) { String line = ""; try {// w w w . j a v a 2 s. co m line = request.getReader().readLine(); } catch (IOException e) { e.printStackTrace(); } String[] msgs = line.split(";;"); List<Request> requests = new ArrayList<Request>(); Gson gson = new GsonBuilder() .registerTypeAdapter(RequestTiming.class, new JsonDeserializer<RequestTiming>() { @Override public RequestTiming deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { if (!jsonElement.isJsonObject()) return new RequestTiming(); String name = ((JsonObject) jsonElement).getAsJsonPrimitive("name").getAsString(); if ("database".equals(name)) { DatabaseTiming databaseTiming = new DatabaseTiming(name); databaseTiming .setTime(((JsonObject) jsonElement).getAsJsonPrimitive("time").getAsLong()); String sql = ((JsonObject) jsonElement).getAsJsonPrimitive("sql").getAsString(); databaseTiming.setSql(sql); List<String> bindingParameters = new ArrayList<String>(); for (JsonElement bindParameter : ((JsonObject) jsonElement).get("bindingParameters") .getAsJsonArray()) { bindingParameters.add(bindParameter.getAsString()); } databaseTiming.setBindingParameters(bindingParameters); return databaseTiming; } RequestTiming requestTiming = new RequestTiming(); requestTiming.setName("server"); requestTiming.setTime(((JsonObject) jsonElement).getAsJsonPrimitive("time").getAsLong()); return requestTiming; } }).create(); for (int i = 0; i < msgs.length - 1; i++) { if (null != msgs[i] && !"".equals(msgs[i])) { requests.add(gson.fromJson(msgs[i], Request.class)); } } String jvmMsg = msgs[msgs.length - 1]; JVM jvm = gson.fromJson(jvmMsg, JVM.class); Metric<JVM> avgThreadCpuTime = jvm.getAvgThreadCpuTime(); setParent(jvm, avgThreadCpuTime); Metric<JVM> committedHeap = jvm.getCommittedHeap(); setParent(jvm, committedHeap); Metric<JVM> usedHeap = jvm.getUsedHeap(); setParent(jvm, usedHeap); Metric<JVM> gcOverhead = jvm.getGcOverhead(); setParent(jvm, gcOverhead); Metric<JVM> threadsCount = jvm.getThreadsCount(); setParent(jvm, threadsCount); ApplicationServer server = APMPrototype.getRoot().getAppServer(); server.setRequests(requests); if (server.getJvm() == null) server.creatJVM(jvm.getName(), jvm.getVersion(), jvm.getArchitecture()); JVM storedJvm = server.getJvm(); storedJvm.setName(jvm.getName()); storedJvm.setArchitecture(jvm.getArchitecture()); storedJvm.setVersion(jvm.getVersion()); mergeJVM(jvm, storedJvm); }
From source file:com.diversityarrays.dalclient.DalUtil.java
License:Open Source License
/** * Parse the input json string and return the parse result if it is a JsonObject. * This is because a valid DAL JSON response is always and only of that structure. * @param json/*ww w.j a va 2 s. com*/ * @return either JsonResult or null if the input cannot be parsed * @throws DalResponseFormatException */ public static JsonResult parseJson(String requestUrl, String json) throws DalResponseFormatException { JsonResult result = null; try { JsonElement jsonElement = new JsonParser().parse(json); if (!jsonElement.isJsonObject()) { throw new DalResponseFormatException( String.format("input is not a JsonObject: %s", jsonElement.getClass().getName())); } result = new JsonResultImpl(requestUrl, (JsonObject) jsonElement); } catch (JsonSyntaxException e) { throw new DalResponseFormatException(e); } return result; }
From source file:com.diversityarrays.dalclient.DalUtil.java
License:Open Source License
static public DalResponseRecord createFrom(String requestUrl, String tagName, JsonObject input) { DalResponseRecord result = new DalResponseRecord(requestUrl, tagName); for (Map.Entry<String, JsonElement> entry : input.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (value == null || value.isJsonNull()) { result.rowdata.put(key, ""); } else if (value.isJsonArray()) { JsonArray array = (JsonArray) value; int count = 0; for (JsonElement elt : array) { if (elt != null && elt.isJsonObject()) { JsonObject child = (JsonObject) elt; Map<String, String> childMap = asRowdata(child); if (childMap != null) { result.addNestedData(key, childMap); }/*from w w w . j a v a2s. c om*/ } else { result.warnings.add(String.format("unexpected value-type for '%s'[%d] :%s", //$NON-NLS-1$ key, count, elt == null ? "null" : elt.getClass().getName())); } ++count; } } else if (value.isJsonPrimitive()) { JsonPrimitive prim = (JsonPrimitive) value; result.rowdata.put(key, prim.getAsString()); } else if (value.isJsonObject()) { // ?? perhaps Map<String, String> childMap = asRowdata((JsonObject) value); if (childMap != null) { result.addNestedData(key, childMap); } } else { result.warnings.add(String.format("unexpected value-type for '%s' :%s", //$NON-NLS-1$ key, value.getClass().getName())); } } return result; }
From source file:com.dozersoftware.snap.PosRepProcessor.java
License:Open Source License
public Message http(Message message) throws ActionProcessingException { System.out.println("&&&&&&&&&&&&&&&& PosRepProcessor &&&&&&&&&&&&&&&&&&&&&"); System.out.println(""); System.out.println("Service: " + service); System.out.println(""); // System.out.println("------------Http Request Info (XStream Encoded)-------------------"); // HttpRequest requestInfo = HttpRequest.getRequest(message); // String requestInfoXML; // XStream xstream = new XStream(); // requestInfoXML = xstream.toXML(requestInfo); // System.out.println(requestInfoXML); System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&"); try {/* w w w . j a va2 s. c o m*/ StringWriter sw = new StringWriter(); final Kml kml = new Kml(); Map<URI, Message> msgs = messageStore.getAllMessages("PosRep"); Iterator<URI> it = msgs.keySet().iterator(); System.out.println("Tracking for :" + msgs.size() + " records"); while (it.hasNext()) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); String raw = (String) msgs.get(it.next()).getBody().get(); Document doc = dBuilder.parse(new ByteArrayInputStream(raw.getBytes())); doc.getDocumentElement().normalize(); NodeList body = doc.getElementsByTagName("BODY"); String handle = doc.getDocumentElement().getAttribute("sender"); Node e = body.item(0); System.out.println("SNAP: " + handle + "'s PosRep -> " + e.getTextContent()); JsonElement jse = new JsonParser().parse(e.getTextContent()); if (jse.isJsonObject()) { System.out.println("We got the right thing: " + jse.toString()); JsonArray ja = jse.getAsJsonObject().getAsJsonArray("POSREP"); // {"POSREP": // [16,"Aug 17, 2010 3:11:00 AM","31.74","-111.11"]} Double lat = ja.get(2).getAsDouble(); Double lng = ja.get(3).getAsDouble(); kml.createAndSetPlacemark().withName(handle).withOpen(Boolean.TRUE).createAndSetPoint() .addToCoordinates(lng, lat); } else { System.out.println("Not an Array!"); } } System.out.println("Processed all positions..."); kml.marshal(sw); message.getBody().add(sw.toString()); } catch (DOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JsonParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MessageStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return message; }
From source file:com.drakeet.rebase.api.tool.ResponseTypeAdapterFactory.java
License:Open Source License
@Override public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { final TypeAdapter<T> delegateAdapter = gson.getDelegateAdapter(this, type); final TypeAdapter<JsonElement> jsonElementAdapter = gson.getAdapter(JsonElement.class); return new TypeAdapter<T>() { @Override/* www. j a v a 2s. c o m*/ public void write(JsonWriter out, T value) throws IOException { delegateAdapter.write(out, value); } @Override @SuppressWarnings("PointlessBooleanExpression") public T read(JsonReader in) throws IOException { JsonElement jsonElement = jsonElementAdapter.read(in); if (jsonElement.isJsonObject()) { JsonObject jsonObject = jsonElement.getAsJsonObject(); if (jsonObject.has(ERROR) && jsonObject.get(ERROR).getAsBoolean() == false) { if (jsonObject.has(DATA) && isJson(jsonObject, DATA)) { jsonElement = jsonObject.get(DATA); } } } return delegateAdapter.fromJsonTree(jsonElement); } }.nullSafe(); }
From source file:com.ecwid.mailchimp.MailChimpClient.java
License:Apache License
/** * Execute MailChimp API method./* w w w. ja v a 2s . c o m*/ * * @param method MailChimp API method to be executed * @return execution result */ public <R> R execute(MailChimpMethod<R> method) throws IOException, MailChimpException { final Gson gson = MailChimpGsonFactory.createGson(); JsonElement result = execute(buildUrl(method), gson.toJsonTree(method)); if (result.isJsonObject()) { JsonElement error = result.getAsJsonObject().get("error"); if (error != null) { JsonElement code = result.getAsJsonObject().get("code"); throw new MailChimpException(code.getAsInt(), error.getAsString()); } } return gson.fromJson(result, method.getResultType()); }
From source file:com.edduarte.argus.reader.JsonReader.java
License:Apache License
private void readRecursive(JsonElement root, MutableString collector) { if (root.isJsonObject()) { JsonObject object = (JsonObject) root; object.entrySet().forEach(e -> { collector.append(e.getKey()); collector.append(' '); readRecursive(e.getValue(), collector); collector.append(' '); });//from w w w . j a v a 2 s .co m } else if (root.isJsonArray()) { JsonArray array = (JsonArray) root; array.forEach(child -> { readRecursive(child, collector); collector.append(' '); }); } else if (root.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) root; collector.append(primitive.getAsString()); collector.append(' '); } }
From source file:com.edgebox.eacds.net.CDPostResponse.java
License:Open Source License
public static CDPostResponse build(String json) { CDPostResponse rt = new CDPostResponse(); JsonElement e = new JsonParser().parse(json); rt.json = e.getAsJsonObject();/*ww w . ja va2 s . c o m*/ rt.success = rt.json.get("success").getAsBoolean(); rt.message = rt.json.get("message").getAsString(); rt.errorTrace = rt.json.get("errorTrace").getAsString(); try { rt.data = rt.json.getAsJsonObject("data").getAsJsonObject(); } catch (java.lang.ClassCastException ex) { rt.data = rt.json.get("data").getAsString(); } JsonElement dt = rt.json.get("data"); if (dt.isJsonNull()) { rt.data = null; } else if (dt.isJsonObject()) { rt.data = dt.getAsJsonObject(); } else { rt.data = dt.getAsJsonPrimitive(); } return rt; }
From source file:com.elevenpaths.latch.LatchResponse.java
License:Open Source License
/** * @param json a JsonElement created from the response of one of the methods of the Latch API * @throws NullPointerException when the json element is null, preventing the instantiation of the object *///from w ww . jav a 2 s . c o m public LatchResponse(JsonElement json) { if (json.isJsonObject()) { if (json.getAsJsonObject().has("data")) { this.data = json.getAsJsonObject().getAsJsonObject("data"); } if (json.getAsJsonObject().has("error")) { this.error = Error .fromCode(json.getAsJsonObject().getAsJsonObject("error").get("code").getAsString()); } } }