List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:com.pinterest.deployservice.common.AlarmDataFactory.java
License:Apache License
/** * Take a JSON string and convert into a list of Alarm configs. *///w w w. j a v a 2 s . co m public List<AlarmBean> fromJson(String payload) { if (StringUtils.isEmpty(payload)) { return Collections.emptyList(); } List<AlarmBean> configs = new ArrayList<>(); JsonParser parser = new JsonParser(); JsonObject jsonObj = (JsonObject) parser.parse(payload); JsonArray arrayOfUrls = jsonObj.getAsJsonArray(ALARM_ARRAY); for (int i = 0; i < arrayOfUrls.size(); i++) { JsonObject urlObj = arrayOfUrls.get(i).getAsJsonObject(); AlarmBean config = new AlarmBean(); config.setName(urlObj.get(NAME).getAsString()); config.setAlarmUrl(urlObj.get(ALARM_URL).getAsString()); JsonElement element = urlObj.get(METRICS_URL); if (!element.isJsonNull()) { config.setMetricsUrl(element.getAsString()); } configs.add(config); } return configs; }
From source file:com.pinterest.deployservice.common.MetricsDataFactory.java
License:Apache License
/** * Takes a JSON string and returns a corresponding JsonObject. *///from w ww . j a va 2 s . c o m public List<MetricsConfigBean> fromJson(String payload) { if (StringUtils.isEmpty(payload)) { return Collections.emptyList(); } List<MetricsConfigBean> configs = new ArrayList<>(); JsonParser parser = new JsonParser(); JsonObject jsonObj = (JsonObject) parser.parse(payload); JsonArray arrayOfUrls = jsonObj.getAsJsonArray("urlMetricsData"); for (int i = 0; i < arrayOfUrls.size(); i++) { JsonObject urlObj = arrayOfUrls.get(i).getAsJsonObject(); MetricsConfigBean urlConfig = new MetricsConfigBean(); urlConfig.setSpecs(new ArrayList<>()); urlConfig.setTitle(urlObj.get("title").getAsString()); urlConfig.setUrl(urlObj.get("url").getAsString()); JsonArray arrayOfSpecs = urlObj.get("specs").getAsJsonArray(); for (int j = 0; j < arrayOfSpecs.size(); j++) { JsonObject specObj = arrayOfSpecs.get(j).getAsJsonObject(); MetricsSpecBean spec = new MetricsSpecBean(); spec.setColor(specObj.get("color").getAsString()); spec.setMax(Double.parseDouble(specObj.get("max").getAsString())); spec.setMin(Double.parseDouble(specObj.get("min").getAsString())); urlConfig.getSpecs().add(spec); } configs.add(urlConfig); } return configs; }
From source file:com.pinterest.deployservice.common.WebhookDataFactory.java
License:Apache License
/** * Take a JSON string and convert into an EnvWebHookBean object */// w w w.ja v a 2s.co m public EnvWebHookBean fromJson(String json) { EnvWebHookBean EnvWebHookBean = new EnvWebHookBean(); if (StringUtils.isEmpty(json)) { return EnvWebHookBean; } JsonParser parser = new JsonParser(); JsonObject jsonObj = (JsonObject) parser.parse(json); JsonArray arrayOfPreHookJson = jsonObj.getAsJsonArray(PREHOOKS); JsonArray arrayOfPostHookJson = jsonObj.getAsJsonArray(POSTHOOKS); List<WebHookBean> listPre = new ArrayList<>(); for (int i = 0; i < arrayOfPreHookJson.size(); i++) { JsonObject hookObj = arrayOfPreHookJson.get(i).getAsJsonObject(); WebHookBean hook = new WebHookBean(); setProperties(hookObj, hook); listPre.add(hook); } List<WebHookBean> listPost = new ArrayList<>(); for (int j = 0; j < arrayOfPostHookJson.size(); j++) { JsonObject hookObj = arrayOfPostHookJson.get(j).getAsJsonObject(); WebHookBean hook = new WebHookBean(); setProperties(hookObj, hook); listPost.add(hook); } EnvWebHookBean.setPreDeployHooks(listPre); EnvWebHookBean.setPostDeployHooks(listPost); return EnvWebHookBean; }
From source file:com.pinterest.secor.consumer.Consumer.java
License:Apache License
private boolean consumeNextMessage() { Message rawMessage = null;/* ww w.jav a2s .c o m*/ try { boolean hasNext = mMessageReader.hasNext(); if (!hasNext) { return false; } rawMessage = mMessageReader.read(); } catch (ConsumerTimeoutException e) { // We wait for a new message with a timeout to periodically apply the upload policy // even if no messages are delivered. LOG.trace("Consumer timed out", e); } if (rawMessage != null) { // Before parsing, update the offset and remove any redundant data try { mMessageWriter.adjustOffset(rawMessage); } catch (IOException e) { throw new RuntimeException("Failed to adjust offset.", e); } //Split the message to subparts - eventParts int size = 0; try { String rawMessageString = new String(rawMessage.getPayload()); JsonObject obj = new JsonParser().parse(rawMessageString).getAsJsonObject(); JsonArray eventArray = null; JsonArray eventArrayAction = null; JsonArray eventArrayNotic = null; eventArrayAction = obj.getAsJsonArray("action"); eventArrayNotic = obj.getAsJsonArray("notic"); if (eventArrayAction != null && eventArrayNotic != null) { eventArray = eventArrayAction; int i = 0; while (i < eventArrayNotic.size()) { eventArray.add(eventArrayNotic.get(i)); i++; } } else { if (eventArrayAction == null) { eventArray = eventArrayNotic; } else { eventArray = eventArrayAction; } } size = eventArray.size(); int i = 0; while (i < size) { ParsedMessage parsedMessage = null; JsonObject subMessage = new JsonObject(); String na = "NA"; JsonObject temporaryAttributes = null; String temporaryCid = null; String unique = null; subMessage.addProperty("e", ((JsonObject) eventArray.get(i)).get("n").getAsString()); subMessage.addProperty("t", ((JsonObject) eventArray.get(i)).get("t").getAsLong()); JsonElement temp1 = ((JsonObject) eventArray.get(i)).get("a"); if (temp1 == null) temporaryAttributes = null; else temporaryAttributes = temp1.getAsJsonObject(); JsonElement temp2 = ((JsonObject) eventArray.get(i)).get("cid"); if (temp2 == null) temporaryCid = null; else temporaryCid = temp2.getAsString(); if (temporaryAttributes == null && temporaryCid == null) subMessage.addProperty("a", na); else { if (temporaryAttributes == null) subMessage.addProperty("a", temporaryCid); else if (temporaryCid == null) subMessage.add("a", temporaryAttributes); else throw new RuntimeException("Failed to parse message " + rawMessageString); } JsonElement temp3 = obj.get("unique_id"); if (temp3 == null) unique = null; else unique = obj.get("unique_id").getAsString(); if (unique == null) subMessage.addProperty("unique_id", na); else subMessage.addProperty("unique_id", unique); subMessage.addProperty("sdk", obj.get("sdk").getAsString()); subMessage.addProperty("user_id", obj.get("user_id").getAsString()); subMessage.addProperty("DBname", obj.get("DBname").getAsString()); String subMessageString = subMessage.toString(); Message message = new Message(rawMessage.getTopic(), rawMessage.getKafkaPartition(), rawMessage.getOffset(), rawMessage.getKafkaKey(), subMessageString.getBytes(Charset.forName("UTF-8"))); //Parse eventParts and write to corresponding files Message transformedMessage = mMessageTransformer.transform(message); parsedMessage = mMessageParser.parse(transformedMessage); LOG.info("MessageWriteSuccess!!" + new String(parsedMessage.getPayload())); //System.out.println("-----------------------Payload-------"+new String(parsedMessage.getPayload())); final double DECAY = 0.999; mUnparsableMessages *= DECAY; if (parsedMessage != null) { try { mMessageWriter.write(parsedMessage); } catch (Exception e) { throw new RuntimeException("Failed to write message " + parsedMessage, e); } } i++; } } catch (Throwable e) { mUnparsableMessages++; final double MAX_UNPARSABLE_MESSAGES = 1000.; if (mUnparsableMessages > MAX_UNPARSABLE_MESSAGES) { LOG.warn("Number of unparsable messages exceeded limit!!!"); //throw new RuntimeException("UNPARSABLE MESSAGES LIMIT EXCEEDED" + rawMessage, e); } LOG.warn("Failed to parse message {}", rawMessage, e); } } return true; }
From source file:com.platzi.silmood.the_fm.io.deserializer.ArtistInfoResponseDeserializer.java
License:Apache License
@Override public Artist deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new Gson(); JsonObject artistData = json.getAsJsonObject().getAsJsonObject(JsonKeys.ARTISTS_ARRAY); JsonArray artistImages = artistData.getAsJsonArray(JsonKeys.ARTIST_IMAGES); JsonObject artistStats = artistData.getAsJsonObject(JsonKeys.ARTIST_STATS); Artist artist = Artist.buildArtistFromJson(artistData); artist.extractUrlsFromImagesArray(artistImages); artist.extractStatsFromJson(artistStats); return artist; }
From source file:com.platzi.silmood.the_fm.io.deserializer.HypedArtistsResponseDeserializer.java
License:Apache License
@Override public HypedArtistResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new Gson(); HypedArtistResponse response = gson.fromJson(json, HypedArtistResponse.class); //The artists array will be parsed manually due nested elements JsonObject artistsResponseData = json.getAsJsonObject().getAsJsonObject(JsonKeys.ARTISTS_RESPONSE); JsonArray artistsArray = artistsResponseData.getAsJsonArray(JsonKeys.ARTISTS_ARRAY); response.setArtists(extractArtistsFromJsonArray(artistsArray)); return response; }
From source file:com.platzi.silmood.the_fm.io.deserializer.HypedArtistsResponseDeserializer.java
License:Apache License
private ArrayList<Artist> extractArtistsFromJsonArray(JsonArray artistsArray) { ArrayList<Artist> artists = new ArrayList<>(); for (int i = 0; i < artistsArray.size(); i++) { JsonObject artistData = artistsArray.get(i).getAsJsonObject(); Artist currentArtist = Artist.buildArtistFromJson(artistData) .extractUrlsFromImagesArray(artistData.getAsJsonArray(JsonKeys.ARTIST_IMAGES)); artists.add(currentArtist);//from w ww . ja v a 2 s . c om } return artists; }
From source file:com.platzi.silmood.the_fm.io.deserializer.TopArtistDeserializer.java
License:Apache License
@Override public TopArtistsResponse deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new Gson(); TopArtistsResponse response = gson.fromJson(json, TopArtistsResponse.class); //The artists array will be parsed manually due nested elements JsonObject artistsResponseData = json.getAsJsonObject().getAsJsonObject(JsonKeys.ARTISTS_RESPONSE); JsonArray artistsArray = artistsResponseData.getAsJsonArray(JsonKeys.ARTISTS_ARRAY); response.setArtists(extractArtistsFromJsonArray(artistsArray)); return response; }
From source file:com.plnyyanks.frcnotebook.datafeed.TBADatafeed.java
License:Open Source License
public static String fetchEventDetails_TBAv1(String eventKey) { String data = GET_Request .getWebData("http://www.thebluealliance.com/api/v1/event/details?event=" + eventKey, true); JsonObject eventObject = JSONManager.getAsJsonObject(data); JsonArray teams = eventObject.getAsJsonArray("teams"); JsonArray matches = eventObject.getAsJsonArray("matches"); Event event = new Event(); event.setEventKey(eventKey);/* www . j a v a2 s .c o m*/ String name = eventObject.get("name").getAsString(); event.setEventName(name); String shortName = eventObject.get("short_name").getAsString(); event.setShortName(shortName); String year = eventObject.get("year").getAsString(); event.setEventYear(Integer.parseInt(year)); String location = eventObject.get("location").getAsString(); event.setEventLocation(location); String start = eventObject.get("start_date").getAsString(); event.setEventStart(start); String end = eventObject.get("end_date").getAsString(); event.setEventEnd(end); Log.d(Constants.LOG_TAG, "official: " + eventObject.get("official")); event.setOfficial(eventObject.get("official").getAsBoolean()); long eventResult = StartActivity.db.addEvent(event); if (eventResult == -1) { return "Error writing event to database"; } Iterator<JsonElement> iterator = teams.iterator(); JsonElement teamElement; Team team; long teamResult = 0; while (iterator.hasNext() && teamResult != -1) { teamElement = iterator.next(); team = new Team(); team.setTeamKey(teamElement.getAsString()); team.setTeamNumber(Integer.parseInt(team.getTeamKey().substring(3))); team.addEvent(eventKey); teamResult = StartActivity.db.addTeam(team); } if (teamResult == -1) { return "Error writing teams to database"; } else { if (matches.size() > 0) { TBADatafeed.fetchMatches_TBAv1(matches.toString()); } return "Info downloaded for " + eventKey; } }
From source file:com.pmeade.arya.gson.deserialize.ArrayFieldDeserializer.java
License:Open Source License
/** * Request deserialization of a JSON array into the provided Object. * @param jo JsonObject containing the JsonArray to be deserialized * @param t Object to be populated with the array content * @param field Field of the object to be populated (also identifies the * name of the JsonArray to be deserialized) * @throws IllegalAccessException never thrown (you don't actually believe * what I just told you, right?) *///from ww w.j a va 2 s. c o m public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { // if the provided JsonObject has a key that maps to the field name if (jo.has(field.getName())) { // get the type of the field (which should be an array) Class objType = field.getType(); // while the type is still an array while (objType.isArray()) { // determine the component type (this is an array OF what?) // example: int[][][] -> int[][] -> int[] -> int objType = objType.getComponentType(); } // ask the AryaDeserializer if this is something that needs // to be deserialized (i.e.: a complex object) or if it is // a simple type that can be interpreted directly boolean loadRequired = aryaDeserializer.isLoadRequired(objType); // obtain the JsonArray that contains the data JsonArray ja = jo.getAsJsonArray(field.getName()); // populate the field on the provided object with the data // deserialized from the JSON representation of the object field.set(t, deserializeArray(ja, field.getType(), loadRequired)); } }