/** * Parse through the JSON string received from the server and translate into GameModelJSON object * * @param json String received from the server API * @return The now parsed GameModelJSON object. * @throws GeneralPlayerException * @throws InvalidTurnStatusException * @throws TurnIndexException */ private CatanModel _deserialize(String json) throws TurnIndexException, InvalidTurnStatusException, GeneralPlayerException { JsonElement jelement = new JsonParser().parse(json); JsonObject jobject = jelement.getAsJsonObject(); JsonObject deck = jobject.getAsJsonObject("deck"); JsonObject bank = jobject.getAsJsonObject("bank"); JsonObject chat = jobject.getAsJsonObject("chat"); JsonObject log = jobject.getAsJsonObject("log"); JsonObject map = jobject.getAsJsonObject("map"); JsonArray players = jobject.getAsJsonArray("players"); JsonObject tradeOffer = jobject.getAsJsonObject("tradeOffer"); JsonObject turnTracker = jobject.getAsJsonObject("turnTracker"); int version = jobject.getAsJsonPrimitive("version").getAsInt(); int winner = jobject.getAsJsonPrimitive("winner").getAsInt(); SetResourceManager(bank, players, tradeOffer); SetDevCardManager(players, deck); SetPlayerManager(players, turnTracker); SetMapManager(map); SetChatManager(chat, log); SetTurnManager(turnTracker); return catanModel = new CatanModel( resourceManager, devCardManager, playerManager, mapManager, chatManager, version); }
/** * Validate post request Json object for FlowFilterEntriesResource. * * @param requestBody the request Json object * @return true, if successful */ private boolean validatePost(final JsonObject requestBody) { LOG.trace("Start FlowFilterEntriesResourceValidator#validatePost()"); boolean isValid = false; setInvalidParameter(VtnServiceJsonConsts.FLOWFILTERENTRY); if (requestBody.has(VtnServiceJsonConsts.FLOWFILTERENTRY) && requestBody.get(VtnServiceJsonConsts.FLOWFILTERENTRY).isJsonObject()) { final JsonObject ffEntry = requestBody.getAsJsonObject(VtnServiceJsonConsts.FLOWFILTERENTRY); // validation for mandatory key: seqnum setInvalidParameter(VtnServiceJsonConsts.SEQNUM); if (ffEntry.has(VtnServiceJsonConsts.SEQNUM) && ffEntry.getAsJsonPrimitive(VtnServiceJsonConsts.SEQNUM).getAsString() != null && !ffEntry .getAsJsonPrimitive(VtnServiceJsonConsts.SEQNUM) .getAsString() .trim() .isEmpty()) { isValid = validator.isValidRange( ffEntry.getAsJsonPrimitive(VtnServiceJsonConsts.SEQNUM).getAsString().trim(), VtnServiceJsonConsts.VAL_1, VtnServiceJsonConsts.VAL_65535); } else { isValid = false; } if (isValid) { isValid = validator.isValidFlowFilterEntry(requestBody); } } LOG.trace("Complete FlowFilterEntriesResourceValidator#validatePost()"); return isValid; }
/** * Validate put request Json object for HostAddressResource * * @param requestBody the request Json object * @return true, if successful */ private boolean validatePut(final JsonObject requestBody) { LOG.trace("Start HostAddressResourceValidator#validatePut()"); boolean isValid = false; setInvalidParameter(VtnServiceJsonConsts.IPADDRESS); if (requestBody.has(VtnServiceJsonConsts.IPADDRESS) && requestBody.get(VtnServiceJsonConsts.IPADDRESS).isJsonObject()) { final JsonObject ipaddr = requestBody.getAsJsonObject(VtnServiceJsonConsts.IPADDRESS); // validation for mandatory keys: ipaddr setInvalidParameter(VtnServiceJsonConsts.IPADDR); if (ipaddr.has(VtnServiceJsonConsts.IPADDR) && ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.IPADDR).getAsString() != null) { isValid = validator.isValidIpV4( ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.IPADDR).getAsString().trim()); } if (isValid) { // validation for mandatory keys: netmask setInvalidParameter(VtnServiceJsonConsts.PREFIX); if (ipaddr.has(VtnServiceJsonConsts.PREFIX) && ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.PREFIX).getAsString() != null) { isValid = validator.isValidRange( ipaddr.getAsJsonPrimitive(VtnServiceJsonConsts.PREFIX).getAsString().trim(), VtnServiceJsonConsts.VAL_1, VtnServiceJsonConsts.VAL_30); } else { isValid = false; } } } LOG.trace("Complete HostAddressResourceValidator#validatePut()"); return isValid; }
private void SetChatManager(JsonObject chat, JsonObject log) { List<Line> chatMessages = new ArrayList<Line>(); List<Line> gameHistory = new ArrayList<Line>(); // Get chat info { JsonArray lines = chat.getAsJsonArray("lines"); for (int i = 0; i < lines.size(); i++) { JsonObject line = lines.get(i).getAsJsonObject(); String message = line.getAsJsonPrimitive("message").getAsString(); String source = line.getAsJsonPrimitive("source").getAsString(); Line l = new Line(message, source); chatMessages.add(l); } } // Get log info { JsonArray lines = log.getAsJsonArray("lines"); for (int i = 0; i < lines.size(); i++) { JsonObject line = lines.get(i).getAsJsonObject(); String message = line.getAsJsonPrimitive("message").getAsString(); String source = line.getAsJsonPrimitive("source").getAsString(); Line l = new Line(message, source); gameHistory.add(l); } } this.chatManager = new ChatManager(chatMessages, gameHistory); }
public PropertyMap deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { PropertyMap result = new PropertyMap(); Iterator i$; Map.Entry<String, JsonElement> entry; if ((json instanceof JsonObject)) { JsonObject object = (JsonObject) json; for (i$ = object.entrySet().iterator(); i$.hasNext(); ) { entry = (Map.Entry) i$.next(); if ((entry.getValue() instanceof JsonArray)) { for (JsonElement element : (JsonArray) entry.getValue()) { result.put( entry.getKey(), new Property((String) entry.getKey(), element.getAsString())); } } } } else if ((json instanceof JsonArray)) { for (JsonElement element : (JsonArray) json) { if ((element instanceof JsonObject)) { JsonObject object = (JsonObject) element; String name = object.getAsJsonPrimitive("name").getAsString(); String value = object.getAsJsonPrimitive("value").getAsString(); if (object.has("signature")) { result.put( name, new Property(name, value, object.getAsJsonPrimitive("signature").getAsString())); } else { result.put(name, new Property(name, value)); } } } } return result; }
private void SetTurnManager(JsonObject turnTracker) throws TurnIndexException, InvalidTurnStatusException, GeneralPlayerException { int currentTurn = turnTracker.getAsJsonPrimitive("currentTurn").getAsInt(); String status = turnTracker.getAsJsonPrimitive("status").getAsString(); PlayerTurnTracker playerTurnTracker = new PlayerTurnTracker(currentTurn, TurnType.toEnum(status)); playerManager.setTurnTracker(playerTurnTracker); }
private AlarmSettingModel jsonToSettingsModel(String fieldsJson, String alarmSettingsId) { JsonObject jsonAlarmSettings = _parser.parse(fieldsJson).getAsJsonObject(); int powerSwitch = jsonAlarmSettings.getAsJsonPrimitive("power_switch").getAsInt(); int triggerSwitch = jsonAlarmSettings.getAsJsonPrimitive("trigger_switch").getAsInt(); int duration = jsonAlarmSettings.getAsJsonPrimitive("duration").getAsInt(); return new AlarmSettingModel( alarmSettingsId, (powerSwitch == 1), (triggerSwitch == 1), duration); }
/** * Validate get request Json for List Sessions API. * * @param requestBody the request Json object * @return true, if successful */ private boolean validateGet(final JsonObject requestBody) { LOG.trace("Start SessionResourceValidator#validateGet()"); boolean isValid = true; // validation for key: op setInvalidParameter(VtnServiceJsonConsts.OP); if (requestBody.has(VtnServiceJsonConsts.OP) && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString() != null && !requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.OP).getAsString().isEmpty()) { isValid = validator.isValidOperation(requestBody); } LOG.trace("Complete SessionResourceValidator#validateGet()"); return isValid; }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { Byte b = jo.getAsJsonPrimitive(field.getName()).getAsByte(); field.setByte(t, b); } }
static Error oauth2(WS.HttpResponse response) { if (response.getQueryString().containsKey("error")) { Map<String, String> qs = response.getQueryString(); return new Error(Type.OAUTH, qs.get("error"), qs.get("error_description")); } else if (response .getContentType() .startsWith("text/javascript")) { // Stupid Facebook returns JSON with the wrong encoding JsonObject jsonResponse = response.getJson().getAsJsonObject().getAsJsonObject("error"); return new Error( Type.OAUTH, jsonResponse.getAsJsonPrimitive("type").getAsString(), jsonResponse.getAsJsonPrimitive("message").getAsString()); } else { return new Error(Type.UNKNOWN, null, null); } }
public static JsonPrimitive getMapValue( JsonElement map, String key, Converter converter, String defaultValueStr) { JsonPrimitive defaultValue = null; if (defaultValueStr != null) { defaultValue = new JsonPrimitive(defaultValueStr); if (converter != null) defaultValue = converter.convert(defaultValue); } if (map == null || !map.isJsonArray()) { return defaultValue; } for (JsonElement el : map.getAsJsonArray()) { if (!el.isJsonObject()) { continue; } JsonObject obj = el.getAsJsonObject(); if (!obj.has("name") || !obj.has("value")) { continue; } if (key.equals(obj.getAsJsonPrimitive("name").getAsString())) { JsonElement value = obj.get("value"); if (!value.isJsonPrimitive()) { throw new ConverterException(value, converter, "Expected a JsonPrimitive"); } if (converter != null) value = converter.convert(value); return value.getAsJsonPrimitive(); } } return defaultValue; }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { Character c = jo.getAsJsonPrimitive(field.getName()).getAsCharacter(); field.setChar(t, c); } }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { Long l = jo.getAsJsonPrimitive(field.getName()).getAsLong(); field.setLong(t, l); } }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { Short s = jo.getAsJsonPrimitive(field.getName()).getAsShort(); field.setShort(t, s); } }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { Integer i = jo.getAsJsonPrimitive(field.getName()).getAsInt(); field.setInt(t, i); } }
protected void parse(JsonObject nodeObject) { this.id = nodeObject.getAsJsonPrimitive(GraphSchema.NODE_ID_TAG).getAsString(); this.name = nodeObject.getAsJsonPrimitive(GraphSchema.NODE_NAME_TAG).getAsString(); JsonArray jArray; if (nodeObject.get(GraphSchema.NODE_INPUT_PORT_TAG) != null) { jArray = nodeObject.getAsJsonArray(GraphSchema.NODE_INPUT_PORT_TAG); for (JsonElement jsonElement : jArray) { this.inputPortIDs.add(jsonElement.getAsString()); } } if (nodeObject.get(GraphSchema.NODE_OUTPUT_PORT_TAG) != null) { jArray = nodeObject.getAsJsonArray(GraphSchema.NODE_OUTPUT_PORT_TAG); for (JsonElement jsonElement : jArray) { this.outputPortIDs.add(jsonElement.getAsString()); } } JsonElement jElement = nodeObject.get(GraphSchema.NODE_CONTROL_IN_PORT_TAG); if (jElement != null) { this.controlInPortID = jElement.getAsString(); } if (nodeObject.get(GraphSchema.NODE_CONTROL_OUT_PORT_TAG) != null) { jArray = nodeObject.getAsJsonArray(GraphSchema.NODE_CONTROL_OUT_PORT_TAG); for (JsonElement jsonElement : jArray) { this.controlOutPortIDs.add(jsonElement.getAsString()); } } jElement = nodeObject.get(GraphSchema.NODE_EPR_PORT_TAG); if (jElement != null) { this.eprPortID = jElement.getAsString(); } this.position.x = nodeObject.get(GraphSchema.NODE_X_LOCATION_TAG).getAsInt(); this.position.y = nodeObject.get(GraphSchema.NODE_Y_LOCATION_TAG).getAsInt(); // Parse config element not sure why we used it. // Parse component element. JsonObject configObject = nodeObject.getAsJsonObject(GraphSchema.NODE_CONFIG_TAG); if (configObject != null) { parseConfiguration(configObject); } }
private void SetPlayerManager(JsonArray players, JsonObject turnTracker) { Player[] catanPlayers = new Player[players.size()]; int longestRoad = turnTracker.getAsJsonPrimitive("longestRoad").getAsInt(); int largestArmy = turnTracker.getAsJsonPrimitive("largestArmy").getAsInt(); for (int i = 0; i < players.size(); i++) { if (!players.get(i).isJsonNull()) { JsonObject player = players.get(i).getAsJsonObject(); int index = player.getAsJsonPrimitive("playerIndex").getAsInt(); String name = player.getAsJsonPrimitive("name").getAsString(); String color = player.getAsJsonPrimitive("color").getAsString(); int playerId = player.getAsJsonPrimitive("playerID").getAsInt(); int cities = player.getAsJsonPrimitive("cities").getAsInt(); int settlements = player.getAsJsonPrimitive("settlements").getAsInt(); int roads = player.getAsJsonPrimitive("roads").getAsInt(); int victoryPoints = player.getAsJsonPrimitive("victoryPoints").getAsInt(); Player newPlayer = new Player(); newPlayer.setPoints(victoryPoints); try { newPlayer.setColor(color); } catch (InvalidColorException e) { e.printStackTrace(); } if (longestRoad == index) { newPlayer.setLongestRoad(true); } if (largestArmy == index) { newPlayer.setLargestArmy(true); } newPlayer.setId(playerId); newPlayer.setCitiesRemaining(cities); newPlayer.setSettlementsRemaining(settlements); newPlayer.setRoadsRemaining(roads); newPlayer.setPlayerIndex(index); newPlayer.setName(name); // <========Construct part of player manager here============> catanPlayers[index] = newPlayer; } } // <========Construct player manager here============> PlayerManager newPlayerManager = new PlayerManager(); newPlayerManager.setCatanPlayers(catanPlayers); newPlayerManager.setIndexOfLargestArmy(largestArmy); newPlayerManager.setIndexOfLongestRoad(longestRoad); this.playerManager = newPlayerManager; }
@Override public void setRequestNotSuc(String url, int statusCode, Header[] headers, JsonObject jo) { super.setRequestNotSuc(url, statusCode, headers, jo); ToastUtil.toastAlways(this, jo.getAsJsonPrimitive(HMApi.KEY_MSG).getAsString()); if (url.equals(HMApiUser.CAPTCHA)) { setCaptchaAble(); } }
public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { if (jo.has(field.getName())) { String s = jo.getAsJsonPrimitive(field.getName()).getAsString(); java.util.UUID u = java.util.UUID.fromString(s); field.set(t, u); } }
@Override public SyncDirectory deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject object = (JsonObject) json; String name = object.getAsJsonPrimitive("name").getAsString(); long size = object.getAsJsonPrimitive("size").getAsLong(); long lastModified = object.getAsJsonPrimitive("lastModified").getAsLong(); boolean added = object.getAsJsonPrimitive("added").getAsBoolean(); SyncDirectory dir = new SyncDirectory(name, size, lastModified, added); JsonArray array = object.getAsJsonArray("files"); for (JsonElement file : array) { dir.add(new IndexBuilder().fromJson(file, SyncFile.class)); } return dir; }
private ConfigurationList parseArrayOfEntriesConfig(JsonArray configJsons) { ConfigurationList config = new ConfigurationList(); for (JsonElement itemJsonEl : configJsons) { JsonObject itemJson = itemJsonEl.getAsJsonObject(); String key = itemJson.get("key").getAsString(); JsonPrimitive valueJson = itemJson.getAsJsonPrimitive("value"); config.configuration.add(makeConfigParam(key, valueJson)); } return config; }
public Map func_150881_a(String p_150881_1_) { JsonElement var2 = (new JsonParser()).parse(p_150881_1_); if (!var2.isJsonObject()) { return Maps.newHashMap(); } else { JsonObject var3 = var2.getAsJsonObject(); HashMap var4 = Maps.newHashMap(); Iterator var5 = var3.entrySet().iterator(); while (var5.hasNext()) { Entry var6 = (Entry) var5.next(); StatBase var7 = StatList.getOneShotStat((String) var6.getKey()); if (var7 != null) { TupleIntJsonSerializable var8 = new TupleIntJsonSerializable(); if (((JsonElement) var6.getValue()).isJsonPrimitive() && ((JsonElement) var6.getValue()).getAsJsonPrimitive().isNumber()) { var8.setIntegerValue(((JsonElement) var6.getValue()).getAsInt()); } else if (((JsonElement) var6.getValue()).isJsonObject()) { JsonObject var9 = ((JsonElement) var6.getValue()).getAsJsonObject(); if (var9.has("value") && var9.get("value").isJsonPrimitive() && var9.get("value").getAsJsonPrimitive().isNumber()) { var8.setIntegerValue(var9.getAsJsonPrimitive("value").getAsInt()); } if (var9.has("progress") && var7.func_150954_l() != null) { try { Constructor var10 = var7.func_150954_l().getConstructor(new Class[0]); IJsonSerializable var11 = (IJsonSerializable) var10.newInstance(new Object[0]); var11.func_152753_a(var9.get("progress")); var8.setJsonSerializableValue(var11); } catch (Throwable var12) { logger.warn("Invalid statistic progress in " + this.field_150887_d, var12); } } } var4.put(var7, var8); } else { logger.warn( "Invalid statistic in " + this.field_150887_d + ": Don\'t know what " + (String) var6.getKey() + " is"); } } return var4; } }
public Map a(String var1) { JsonElement var2 = (new JsonParser()).parse(var1); if (!var2.isJsonObject()) { return Maps.newHashMap(); } else { JsonObject var3 = var2.getAsJsonObject(); HashMap var4 = Maps.newHashMap(); Iterator var5 = var3.entrySet().iterator(); while (true) { while (var5.hasNext()) { Entry var6 = (Entry) var5.next(); class_nd var7 = StatisticList.a((String) var6.getKey()); if (var7 != null) { class_nf var8 = new class_nf(); if (((JsonElement) var6.getValue()).isJsonPrimitive() && ((JsonElement) var6.getValue()).getAsJsonPrimitive().isNumber()) { var8.a(((JsonElement) var6.getValue()).getAsInt()); } else if (((JsonElement) var6.getValue()).isJsonObject()) { JsonObject var9 = ((JsonElement) var6.getValue()).getAsJsonObject(); if (var9.has("value") && var9.get("value").isJsonPrimitive() && var9.get("value").getAsJsonPrimitive().isNumber()) { var8.a(var9.getAsJsonPrimitive("value").getAsInt()); } if (var9.has("progress") && (var7.l() != null)) { try { Constructor var10 = var7.l().getConstructor(new Class[0]); class_ng var11 = (class_ng) var10.newInstance(new Object[0]); var11.a(var9.get("progress")); var8.a(var11); } catch (Throwable var12) { b.warn("Invalid statistic progress in " + d, var12); } } } var4.put(var7, var8); } else { b.warn( "Invalid statistic in " + d + ": Don\'t know what " + (String) var6.getKey() + " is"); } } return var4; } } }
@Override public Video deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject root = json.getAsJsonObject(); String id = root.getAsJsonObject("id").getAsJsonPrimitive("videoId").getAsString(); JsonObject snippet = root.getAsJsonObject("snippet"); String title = snippet.getAsJsonPrimitive("title").getAsString(); String desc = snippet.getAsJsonPrimitive("description").getAsString(); String channelId = snippet.getAsJsonPrimitive("channelId").getAsString(); String channelTitle = snippet.getAsJsonPrimitive("channelTitle").getAsString(); Video.Thumbnail thumb = context.deserialize(snippet.get("thumbnails"), Video.Thumbnail.class); Video video = new Video(); video.setId(id); video.setTitle(title); video.setDescription(desc); video.setChannelId(channelId); video.setChannelTitle(channelTitle); video.setThumbnail(thumb); return video; }
/** * Validate put request Json for Set Password API. * * @param requestBody the request Json object * @return true, if successful */ private boolean validatePut(final JsonObject requestBody) { LOG.trace("Start UserResourceValidator#validatePut()"); boolean isValid = false; // validation for password setInvalidParameter(VtnServiceJsonConsts.PASSWORD); if (requestBody.has(VtnServiceJsonConsts.PASSWORD) && requestBody.get(VtnServiceJsonConsts.PASSWORD) instanceof JsonObject && requestBody .get(VtnServiceJsonConsts.PASSWORD) .getAsJsonObject() .getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD) .getAsString() != null) { final String password = requestBody .get(VtnServiceJsonConsts.PASSWORD) .getAsJsonObject() .get(VtnServiceJsonConsts.PASSWORD) .getAsString(); requestBody.remove(VtnServiceJsonConsts.PASSWORD); requestBody.addProperty(VtnServiceJsonConsts.PASSWORD, password); } if (requestBody.has(VtnServiceJsonConsts.PASSWORD) && requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString() != null && !requestBody .getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD) .getAsString() .trim() .isEmpty()) { isValid = validator.isValidMaxLength( requestBody.getAsJsonPrimitive(VtnServiceJsonConsts.PASSWORD).getAsString().trim(), VtnServiceJsonConsts.LEN_72); } else { isValid = false; } LOG.trace("Complete UserResourceValidator#validatePut()"); return isValid; }
/** * Gets the session from json. * * @param sessionObjRes the session obj res * @return the session from json */ public static long getSessionFromJson(final JsonObject sessionObjRes) { LOG.trace("Start VtnServiceCommonUtil#getSessionFromJson()"); long sessionID = -1; if (null != sessionObjRes) { final JsonObject sessionJson = sessionObjRes.getAsJsonObject(ApplicationConstants.SESSION); if (null != sessionJson && sessionJson.has(ApplicationConstants.SESSION_ID_STR)) { sessionID = sessionJson.getAsJsonPrimitive(ApplicationConstants.SESSION_ID_STR).getAsLong(); } } LOG.debug("Session Id : " + sessionID); LOG.trace("Complete VtnServiceCommonUtil#getSessionFromJson()"); return sessionID; }
@Override public void onDataChanged(String s, String s1, String s2, String s3) { System.out.println("Data changed to <" + s + "> in document <" + s1 + ">"); System.out.println(" Changed: " + s2); JsonObject jsonAlarmSettings = _parser.parse(s2).getAsJsonObject(); JsonPrimitive jsonPS = jsonAlarmSettings.getAsJsonPrimitive("power_switch"); JsonPrimitive jsonTS = jsonAlarmSettings.getAsJsonPrimitive("trigger_switch"); JsonPrimitive jsonDuration = jsonAlarmSettings.getAsJsonPrimitive("duration"); if (jsonPS != null) { int powerSwitch = jsonPS.getAsInt(); _model.setPowerSwitch((powerSwitch == 1)); } else if (jsonTS != null) { int triggerSwitch = jsonTS.getAsInt(); _model.setTriggerSwitch((triggerSwitch == 1)); } else if (jsonDuration != null) { int duration = jsonDuration.getAsInt(); _model.setDurationSeconds(duration); } _callback.callback(null, _model); }
/** * Gets the config id from json. * * @param configObjRes the config obj res * @return the config id from json */ public static long getConfigIdFromJson(final JsonObject configObjRes) { LOG.trace("Start VtnServiceCommonUtil#getConfigIdFromJson()"); long configID = -1; if (null != configObjRes) { final JsonObject configModeJson = configObjRes.getAsJsonObject(ApplicationConstants.CONFIG_MODE); if (null != configModeJson && configModeJson.has(ApplicationConstants.CONFIG_ID_STR)) { configID = configModeJson.getAsJsonPrimitive(ApplicationConstants.CONFIG_ID_STR).getAsInt(); } } LOG.debug("Config Id : " + configID); LOG.trace("Complete VtnServiceCommonUtil#getConfigIdFromJson()"); return configID; }
/** * This private operation creates an instance of the Message class from a string using a JSON * parser. * * <p>This operation is synchronized so that the core can't be overloaded. * * @param messageString The original message, as a string * @return list list of built messages. */ private ArrayList<Message> buildMessagesFromString(String messageString) { // Create the ArrayList of messages ArrayList<Message> messages = new ArrayList<Message>(); // Create the parser and gson utility JsonParser parser = new JsonParser(); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); // Catch any exceptions and return the empty list try { // Make the string a json string JsonElement messageJson = parser.parse(messageString); JsonObject messageJsonObject = messageJson.getAsJsonObject(); // Get the Item id from the json JsonPrimitive itemIdJson = messageJsonObject.getAsJsonPrimitive("item_id"); int itemId = itemIdJson.getAsInt(); // Get the array of posts from the message JsonArray jsonMessagesList = messageJsonObject.getAsJsonArray("posts"); // Load the list for (int i = 0; i < jsonMessagesList.size(); i++) { // Get the message as a json element JsonElement jsonMessage = jsonMessagesList.get(i); // Marshal it into a message Message tmpMessage = gson.fromJson(jsonMessage, Message.class); // Set the item id tmpMessage.setItemId(itemId); // Put it in the list messages.add(tmpMessage); } } catch (JsonParseException e) { // Log the message String err = "Core Message: " + "JSON parsing failed for message " + messageString; logger.error(getClass().getName() + " Exception!", e); logger.error(err); } return messages; }
@Override public SageInteract deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); JsonElement control = jsonObject.get(KEY_CONTROLS); varNames = new ArrayList<String>(); controls = new ArrayList<InteractControl>(); // Here we modify the model slightly and add the varName indirectly to our InteractControl // by obtaining it from the list of keys from the JSON and passing the // This way, we can continue to use Gson for the normal deserialization of // our InteractControl class // Get all the possible keys for InteractControl Log.i(TAG, "Got Control" + control.toString()); Log.i(TAG, "No. of controls " + control.getAsJsonObject().entrySet().size()); // Iterate through keys and deserialize for (Map.Entry<String, JsonElement> keys : control.getAsJsonObject().entrySet()) { varNames.add(keys.getKey()); Log.i(TAG, "Got Key: " + keys.getKey()); InteractControl interactControl = context.deserialize(keys.getValue(), InteractControl.class); Log.i(TAG, "Deserializing: " + interactControl.toString()); interactControl.setVarName(keys.getKey()); controls.add(interactControl); } // TODO Find way to add the omitted data final SageInteract interact = new SageInteract(); interact.setControls(controls); interact.setNewInteractID(jsonObject.getAsJsonPrimitive(KEY_NEW_INTERACT_ID).getAsString()); return interact; }