private static void readJsonFile() { try (JsonReader jsonReader = Json.createReader( new FileReader( Paths.get(System.getProperty("user.dir"), "target/myData.json").toString()))) { JsonStructure jsonStructure = jsonReader.read(); JsonValue.ValueType valueType = jsonStructure.getValueType(); if (valueType == JsonValue.ValueType.OBJECT) { JsonObject jsonObject = (JsonObject) jsonStructure; JsonValue firstName = jsonObject.get("firstName"); LOGGER.info("firstName=" + firstName); JsonValue emailAddresses = jsonObject.get("phoneNumbers"); if (emailAddresses.getValueType() == JsonValue.ValueType.ARRAY) { JsonArray jsonArray = (JsonArray) emailAddresses; for (int i = 0; i < jsonArray.size(); i++) { JsonValue jsonValue = jsonArray.get(i); LOGGER.info("emailAddress(" + i + "): " + jsonValue); } } } else { LOGGER.warning("First object is not of type " + JsonValue.ValueType.OBJECT); } } catch (FileNotFoundException e) { LOGGER.severe("Failed to open file: " + e.getMessage()); } }
private FlickrPhoto buildInfo(JsonReader jsonReader) { JsonObject jobj = jsonReader.readObject(); JsonObject object = (JsonObject) jobj.get("photo"); String id = object.getString("id"); FlickrPhoto p = photos.getPhoto(id); if (p == null) { p = new FlickrPhoto(); p.id = id; photos.setPhoto(p); } p.id = id; // JsonArray array = (JsonArray) object.get("dates"); object = (JsonObject) object.get("dates"); logger.debug("date=" + object.getString("taken")); logger.debug( "dateTaken=" + FlickrPhotoDate.setDateInFlickrTextFormat(object.getString("taken"))); p.dateTaken = FlickrPhotoDate.setDateInFlickrTextFormat(object.getString("taken")); logger.debug("DateTaken=" + p.dateTaken); return p; }
@POST public JsonObject saveBook(final JsonObject book) { long id = System.nanoTime(); JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); JsonObject newBook = jsonObjectBuilder .add("bookId", id) .add("bookName", book.get("bookName")) .add("publisher", book.get("publisher")) .build(); BookResource.memoryBase.put(id, newBook); return newBook; }
public static void dumpJSON(JsonValue tree, String key, String depthPrefix) { if (key != null) logger.info(depthPrefix + "Key " + key + ": "); switch (tree.getValueType()) { case OBJECT: logger.info(depthPrefix + "OBJECT"); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) dumpJSON(object.get(name), name, depthPrefix + " "); break; case ARRAY: logger.info(depthPrefix + "ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) dumpJSON(val, null, depthPrefix + " "); break; case STRING: JsonString st = (JsonString) tree; logger.info(depthPrefix + "STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; logger.info(depthPrefix + "NUMBER " + num.toString()); break; case TRUE: case FALSE: case NULL: logger.info(depthPrefix + tree.getValueType().toString()); break; } }
public ListItemReader<JsonObject> setResource() throws MalformedURLException { // Date date = new Date(); // String today= new SimpleDateFormat("yyyyMMdd").format(date); // local time이 일치하지 않으므로, 전날 종료된 경기정보 업데이트이므로 date -1 Calendar cal = Calendar.getInstance(); cal.add(Calendar.DATE, -1); String today = new SimpleDateFormat("yyyyMMdd").format(cal.getTime()); URL url = new URL("http://data.nba.com/data//json/nbacom/2015/gameline/" + today + "/games.json"); try (InputStream is = url.openStream(); JsonReader rdr = Json.createReader(is)) { JsonObject obj = rdr.readObject(); if (obj != null && obj.get("games") != null && obj.getJsonArray("games").size() > 0) { for (int idx = 0; idx < obj.getJsonArray("games").size(); idx++) { items.add(obj.getJsonArray("games").getJsonObject(idx)); } } } catch (IOException e) { e.printStackTrace(); } ListItemReader<JsonObject> reader = new ListItemReader<>(this.items); return reader; }
/** * Get long value out of the message json payload * * @param key Key to find value for * @param defaultValue Default value if key can't be found * @return value in object, or the provided default */ public long getLong(String key, long defaultValue) { JsonObject obj = getParsedBody(); JsonValue value = obj.get(key); if (value != null && value.getValueType() == ValueType.NUMBER) { return ((JsonNumber) value).longValue(); } return defaultValue; }
/** * @param key * @return JsonObject value or null */ public JsonObject getObject(String key) { JsonObject obj = getParsedBody(); JsonValue value = obj.get(key); if (value != null && value.getValueType() == ValueType.OBJECT) { return (JsonObject) value; } return null; }
/** * Get boolean value out of the message json payload * * @param key Key to find value for * @param defaultValue Default value if key can't be found * @return value in object, or the provided default */ public boolean getBoolean(String key, boolean defaultValue) { JsonObject obj = getParsedBody(); JsonValue value = obj.get(key); if (value != null) { if (value.getValueType() == ValueType.FALSE) return false; if (value.getValueType() == ValueType.TRUE) return true; } return defaultValue; }
/** * @see org.jivesoftware.smack.PacketListener#processPacket(org.jivesoftware.smack.packet.Packet) */ @Override public void processPacket(Packet packet) { Message incomingMessage = (Message) packet; GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GcmPacketExtension.GCM_NAMESPACE); String json = gcmPacket.getJson(); JsonReader jsonReader = Json.createReader(new StringReader(json)); JsonObject jsonObject = jsonReader.readObject(); Object messageType = jsonObject.get("message_type"); System.out.println(messageType); }
// Update the existing album with `id`. // // Display the modified album. private void actionPutAlbum(Router router, Request request, String id) { JsonReader reader = Json.createReader(new StringReader(request.body)); JsonObject album = reader.readObject(); for (JsonObject oalbum : catalog.getValuesAs(JsonObject.class)) { if (oalbum.getString("id").equals(id)) { JsonObjectBuilder builder = Json.createObjectBuilder(); for (String key : oalbum.keySet()) { builder.add(key, oalbum.get(key)); } for (String key : album.keySet()) { builder.add(key, album.get(key)); } // TODO add model layer and data management router.sendJsonResponse(200, "OK", builder.build()); return; } } // No album with this ID found, return error router.sendJsonError(404, "Not found"); }
private void readResultJson(JsonObject object) { if (object.get("api_quest_name") != null) { this.questName = object.getString("api_quest_name"); } else { // 演習の場合はない this.questName = null; } this.rank = ResultRank.fromRank(object.getString("api_win_rank")); // 完全勝利Sは分からないので戦闘結果を見る Phase lastPhase = this.getLastPhase(); if ((lastPhase != null) && (lastPhase.getEstimatedRank() == ResultRank.PERFECT)) { this.rank = ResultRank.PERFECT; } this.enemyName = object.getJsonObject("api_enemy_info").getString("api_deck_name"); this.dropShip = object.containsKey("api_get_ship"); this.dropItem = object.containsKey("api_get_useitem"); if (this.dropShip || this.dropItem) { if (this.dropShip) { JsonObject getShip = object.getJsonObject("api_get_ship"); this.dropShipId = getShip.getInt("api_ship_id"); this.dropType = getShip.getString("api_ship_type"); this.dropName = getShip.getString("api_ship_name"); } else { String name = UseItem.get(object.getJsonObject("api_get_useitem").getInt("api_useitem_id")); this.dropType = "アイテム"; this.dropName = StringUtils.defaultString(name); } } else { this.dropType = ""; this.dropName = ""; } this.mvp = object.getInt("api_mvp"); if (JsonUtils.hasKey(object, "api_mvp_combined")) { this.mvpCombined = object.getInt("api_mvp_combined"); } this.hqLv = object.getInt("api_member_lv"); if (JsonUtils.hasKey(object, "api_escape")) { JsonObject jsonEscape = object.getJsonObject("api_escape"); this.escapeInfo = new int[] { jsonEscape.getJsonArray("api_escape_idx").getInt(0) - 1, jsonEscape.getJsonArray("api_tow_idx").getInt(0) - 1 }; } if (JsonUtils.hasKey(object, "api_lost_flag")) { this.lostflag = new boolean[6]; JsonArray jsonLostflag = object.getJsonArray("api_lost_flag"); for (int i = 1; i < jsonLostflag.size(); i++) { this.lostflag[i - 1] = (jsonLostflag.getInt(i) != 0); } } }
public static int navigateTree(JsonValue tree, String skip) { int ret = 0; switch (tree.getValueType()) { case OBJECT: // System.out.println("OBJECT"); JsonArrayBuilder dirtyResult = Json.createArrayBuilder(); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) { if (object.get(name).getValueType() == JsonValue.ValueType.STRING && object.getString(name).equals(skip)) { return 0; } dirtyResult.add(object.get(name)); } ret = ret + navigateTree(dirtyResult.build(), skip); break; case ARRAY: // System.out.println("ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) ret = ret + navigateTree(val, skip); break; case STRING: JsonString st = (JsonString) tree; // System.out.println("STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; return num.intValue(); case TRUE: case FALSE: case NULL: // System.out.println(tree.getValueType().toString()); break; } return ret; }
/** * @param key * @return JsonArray value or null */ public List<Long> getLongArray(String key, List<Long> defaultValue) { JsonObject obj = getParsedBody(); JsonValue arrayValue = obj.get(key); if (arrayValue != null && arrayValue.getValueType() == ValueType.ARRAY) { try { List<Long> result = new ArrayList<>(); ((JsonArray) arrayValue).forEach(value -> result.add(((JsonNumber) value).longValue())); return result; } catch (Exception e) { // class cast, etc Log.log(Level.FINER, this, "Exception parsing JsonArray: " + arrayValue, e); // fall through to return default value } } return defaultValue; }
/** * Get optional long value out of the message json payload * * @param key Key to find value for * @return value in object or null */ public String getString(String key) { String result = null; JsonObject obj = getParsedBody(); JsonValue value = obj.get(key); if (value != null) { try { if (value.getValueType() == ValueType.STRING) { result = obj.getString(key); } else { result = value.toString(); } } catch (Exception e) { // class cast, etc Log.log(Level.FINER, this, "Exception parsing String: " + value, e); // fall through to return default value } } return result; }
public static <T extends Factory> T objectFromJson(JsonObject json, T prototype) throws ParseException { T object = (T) prototype.create(); Method[] methods = object.getClass().getMethods(); for (final Method method : methods) { if (method.getName().startsWith("set") && method.getParameterTypes().length == 1) { final String name = Introspector.decapitalize(method.getName().substring(3)); Class<?> parameterType = method.getParameterTypes()[0]; if (json.containsKey(name)) try { if (parameterType.equals(boolean.class)) { method.invoke(object, json.getBoolean(name)); } else if (parameterType.equals(int.class)) { method.invoke(object, json.getJsonNumber(name).intValue()); } else if (parameterType.equals(long.class)) { if (json.get(name).getValueType() == JsonValue.ValueType.NUMBER) { method.invoke(object, json.getJsonNumber(name).longValue()); } } else if (parameterType.equals(double.class)) { method.invoke(object, json.getJsonNumber(name).doubleValue()); } else if (parameterType.equals(String.class)) { method.invoke(object, json.getString(name)); } else if (parameterType.equals(Date.class)) { method.invoke(object, dateFormat.parse(json.getString(name))); } else if (parameterType.equals(Map.class)) { method.invoke(object, MiscFormatter.fromJson(json.getJsonObject(name))); } } catch (IllegalAccessException | InvocationTargetException error) { } } } return object; }
/** * http://docs.oracle.com/middleware/1213/wls/WLPRG/java-api-for-json-proc.htm#WLPRG1061 * * @param tree * @param key */ public static Object navigateTree(JsonValue tree, String key) { Object ret = null; if (key != null) System.out.print("Key " + key + ": "); switch (tree.getValueType()) { case OBJECT: System.out.println("OBJECT"); JsonObject object = (JsonObject) tree; for (String name : object.keySet()) navigateTree(object.get(name), name); break; case ARRAY: System.out.println("ARRAY"); JsonArray array = (JsonArray) tree; for (JsonValue val : array) navigateTree(val, null); break; case STRING: JsonString st = (JsonString) tree; System.out.println("STRING " + st.getString()); break; case NUMBER: JsonNumber num = (JsonNumber) tree; System.out.println("NUMBER " + num.toString()); break; case TRUE: System.out.println("TRUE"); case FALSE: System.out.println("FALSE"); case NULL: System.out.println(tree.getValueType().toString()); break; } return ret; }
/** * 戦闘フェーズ結果を読み込む * * @param object 受け取ったJSON * @param kind 戦闘の種別 * @return 作成されたPhaseオブジェクト */ public Phase addPhase(JsonObject object, BattlePhaseKind kind) { if (this.phaseList.size() == 0) { // 最初のフェーズ String dockId; if (object.containsKey("api_dock_id")) { dockId = object.get("api_dock_id").toString(); } else { dockId = object.get("api_deck_id").toString(); } JsonArray nowhps = object.getJsonArray("api_nowhps"); JsonArray maxhps = object.getJsonArray("api_maxhps"); JsonArray nowhpsCombined = object.getJsonArray("api_nowhps_combined"); JsonArray maxhpsCombined = object.getJsonArray("api_maxhps_combined"); boolean isCombined = (nowhpsCombined != null); int numFships = 6; int numFshipsCombined = 0; for (int i = 1; i <= 6; ++i) { if (maxhps.getInt(i) == -1) { numFships = i - 1; break; } } if (object.containsKey("api_fParam_combined")) { numFshipsCombined = 6; for (int i = 1; i <= 6; ++i) { if (maxhpsCombined.getInt(i) == -1) { numFshipsCombined = i - 1; break; } } } if (this.friends.size() == 0) { // 再読み込みの場合はスキップ this.friends.add(GlobalContext.getDock(dockId)); if (numFshipsCombined > 0) { this.friends.add(GlobalContext.getDock("2")); } } JsonArray shipKe = object.getJsonArray("api_ship_ke"); JsonArray eSlots = object.getJsonArray("api_eSlot"); JsonArray eParams = object.getJsonArray("api_eParam"); JsonArray eLevel = object.getJsonArray("api_ship_lv"); for (int i = 1; i < shipKe.size(); i++) { int id = shipKe.getInt(i); if (id != -1) { int[] slot = JsonUtils.toIntArray(eSlots.getJsonArray(i - 1)); int[] param = JsonUtils.toIntArray(eParams.getJsonArray(i - 1)); this.enemy.add(new EnemyShipDto(id, slot, param, eLevel.getInt(i))); } } int numEships = this.enemy.size(); this.startFriendHp = new int[numFships]; this.startEnemyHp = new int[numEships]; this.maxFriendHp = new int[numFships]; this.maxEnemyHp = new int[numEships]; if (isCombined) { this.startFriendHpCombined = new int[numFshipsCombined]; this.maxFriendHpCombined = new int[numFshipsCombined]; } else { this.maxFriendHpCombined = null; } // 陣形 if (object.containsKey("api_formation")) { JsonArray formation = object.getJsonArray("api_formation"); for (int i = 0; i < 2; ++i) { switch (formation.get(i).getValueType()) { case NUMBER: this.formation[i] = toFormation(formation.getInt(i)); break; default: this.formation[i] = toFormation(Integer.parseInt(formation.getString(i))); } } this.formationMatch = toMatch(formation.getInt(2)); } // 索敵 JsonArray jsonSearch = object.getJsonArray("api_search"); if (jsonSearch != null) { this.sakuteki = new String[] {toSearch(jsonSearch.getInt(0)), toSearch(jsonSearch.getInt(1))}; } // この戦闘の開始前HPを取得 for (int i = 1; i < nowhps.size(); i++) { int hp = nowhps.getInt(i); int maxHp = maxhps.getInt(i); if (i <= 6) { if (i <= numFships) { this.maxFriendHp[i - 1] = maxHp; this.friendGaugeMax += this.startFriendHp[i - 1] = hp; } } else { if ((i - 6) <= numEships) { this.maxEnemyHp[i - 1 - 6] = maxHp; this.enemyGaugeMax += this.startEnemyHp[i - 1 - 6] = hp; } } } if (isCombined) { for (int i = 1; i < nowhpsCombined.size(); i++) { int hp = nowhpsCombined.getInt(i); int maxHp = maxhpsCombined.getInt(i); if (i <= numFshipsCombined) { this.maxFriendHpCombined[i - 1] = maxHp; this.friendGaugeMax += this.startFriendHpCombined[i - 1] = hp; } } // 退避 this.escaped = new boolean[12]; if (JsonUtils.hasKey(object, "api_escape_idx")) { for (JsonValue jsonShip : object.getJsonArray("api_escape_idx")) { this.escaped[((JsonNumber) jsonShip).intValue() - 1] = true; } } if (JsonUtils.hasKey(object, "api_escape_idx_combined")) { for (JsonValue jsonShip : object.getJsonArray("api_escape_idx_combined")) { this.escaped[(((JsonNumber) jsonShip).intValue() - 1) + 6] = true; } } for (int i = 0; i < 2; ++i) { this.friends.get(i).setEscaped(Arrays.copyOfRange(this.escaped, i * 6, (i + 1) * 6)); } } } if (this.phaseList.size() > 0) { Phase phase = this.phaseList.get(0); this.completeDamageAndAddPhase( new Phase( this, object, kind, phase.getNowFriendHp(), phase.getNowFriendHpCombined(), phase.getNowEnemyHp()), kind); } else { this.completeDamageAndAddPhase( new Phase( this, object, kind, this.startFriendHp, this.startFriendHpCombined, this.startEnemyHp), kind); } return this.phaseList.get(this.phaseList.size() - 1); }
public Phase( BattleExDto battle, JsonObject object, BattlePhaseKind kind, int[] beforeFriendHp, int[] beforeFriendHpCombined, int[] beforeEnemyHp) { boolean isCombined = (beforeFriendHpCombined != null); this.kind = kind; this.isNight = kind.isNight(); this.nowFriendHp = beforeFriendHp.clone(); this.nowEnemyHp = beforeEnemyHp.clone(); if (isCombined) { this.nowFriendHpCombined = beforeFriendHpCombined.clone(); } else { this.nowFriendHpCombined = null; } // 夜間触接 JsonValue jsonTouchPlane = object.get("api_touch_plane"); if ((jsonTouchPlane != null) && (jsonTouchPlane != JsonValue.NULL)) { this.touchPlane = JsonUtils.getIntArray(object, "api_touch_plane"); } // 照明弾発射艦 JsonValue jsonFlarePos = object.get("api_flare_pos"); if ((jsonFlarePos != null) && (jsonFlarePos != JsonValue.NULL)) { this.flarePos = JsonUtils.getIntArray(object, "api_flare_pos"); } // 攻撃シーケンスを読み取る // // 航空戦(通常) JsonObject kouku = object.getJsonObject("api_kouku"); if (kouku != null) { this.air = new AirBattleDto(kouku, isCombined); // 昼戦の触接はここ this.touchPlane = this.air.touchPlane; // 制空はここから取る this.seiku = this.air.seiku; } // 支援艦隊 JsonNumber support_flag = object.getJsonNumber("api_support_flag"); if ((support_flag != null) && (support_flag.intValue() != 0)) { JsonObject support = object.getJsonObject("api_support_info"); JsonValue support_hourai = support.get("api_support_hourai"); JsonValue support_air = support.get("api_support_airatack"); if ((support_hourai != null) && (support_hourai != JsonValue.NULL)) { JsonArray edam = ((JsonObject) support_hourai).getJsonArray("api_damage"); if (edam != null) { this.support = BattleAtackDto.makeSupport(edam); } } else if ((support_air != null) && (support_air != JsonValue.NULL)) { JsonValue stage3 = ((JsonObject) support_air).get("api_stage3"); if ((stage3 != null) && (stage3 != JsonValue.NULL)) { this.support = BattleAtackDto.makeSupport(((JsonObject) stage3).getJsonArray("api_edam")); } } this.supportType = toSupport(support_flag.intValue()); } else { this.supportType = ""; } // 航空戦(連合艦隊のみ?) JsonObject kouku2 = object.getJsonObject("api_kouku2"); if (kouku2 != null) this.air2 = new AirBattleDto(kouku2, isCombined); // 開幕 this.opening = BattleAtackDto.makeRaigeki(object.get("api_opening_atack"), kind.isOpeningSecond()); // 砲撃 this.hougeki = BattleAtackDto.makeHougeki(object.get("api_hougeki"), kind.isHougekiSecond()); // 夜戦 this.hougeki1 = BattleAtackDto.makeHougeki(object.get("api_hougeki1"), kind.isHougeki1Second()); this.hougeki2 = BattleAtackDto.makeHougeki(object.get("api_hougeki2"), kind.isHougeki2Second()); this.hougeki3 = BattleAtackDto.makeHougeki(object.get("api_hougeki3"), kind.isHougeki3Second()); // 雷撃 this.raigeki = BattleAtackDto.makeRaigeki(object.get("api_raigeki"), kind.isRaigekiSecond()); // ダメージを反映 // if (this.air != null) this.doAtack(this.air.atacks); this.doAtack(this.support); if (this.air2 != null) this.doAtack(this.air2.atacks); this.doAtack(this.opening); this.doAtack(this.hougeki); this.doAtack(this.hougeki1); this.doAtack(this.raigeki); this.doAtack(this.hougeki2); this.doAtack(this.hougeki3); this.json = object.toString(); }