private void mergeUpdate(JsonObject update, JsonObject master) { for (Map.Entry<String, JsonElement> attr : update.entrySet()) { if ((null == attr.getValue()) || attr.getValue().isJsonNull()) { // TODO use singleton to reduce memory footprint master.add(attr.getKey(), new JsonNull()); } assertCompatibility(master.get(attr.getKey()), attr.getValue()); if (attr.getValue() instanceof JsonPrimitive) { if (!master.has(attr.getKey()) || !master.get(attr.getKey()).equals(attr.getValue())) { master.add(attr.getKey(), attr.getValue()); } } else if (attr.getValue() instanceof JsonObject) { if (!master.has(attr.getKey()) || master.get(attr.getKey()).isJsonNull()) { // copy whole subtree master.add(attr.getKey(), attr.getValue()); } else { // recurse to merge attribute updates mergeUpdate( attr.getValue().getAsJsonObject(), master.get(attr.getKey()).getAsJsonObject()); } } else if (attr.getValue() instanceof JsonArray) { // TODO any way to correlate elements between arrays? will need concept of // element identity to merge elements master.add(attr.getKey(), attr.getValue()); } } }
@Override public JsonElement serialize( FirewallOptions src, Type typeOfSrc, JsonSerializationContext context) { JsonObject firewall = new JsonObject(); if (src.getName() != null) { firewall.addProperty("name", src.getName()); } if (src.getNetwork() != null) { firewall.addProperty("network", src.getNetwork().toString()); } if (!src.getSourceRanges().isEmpty()) { firewall.add("sourceRanges", buildArrayOfStrings(src.getSourceRanges())); } if (!src.getSourceTags().isEmpty()) { firewall.add("sourceTags", buildArrayOfStrings(src.getSourceTags())); } if (!src.getTargetTags().isEmpty()) { firewall.add("targetTags", buildArrayOfStrings(src.getTargetTags())); } if (!src.getAllowed().isEmpty()) { JsonArray rules = new JsonArray(); for (Rule rule : src.getAllowed()) { rules.add(context.serialize(rule, Firewall.Rule.class)); } firewall.add("allowed", rules); } return firewall; }
public void load() throws IOException { File file = getFile(); if (file.exists()) { JsonObject rootObject = JSON_PARSER.parse(new FileReader(file)).getAsJsonObject(); for (JsonElement element : rootObject.getAsJsonArray("players")) { Player player = new Player(element.getAsJsonObject()); playerDB.put(player.getName(), player); } for (JsonElement element : rootObject.getAsJsonArray("groups")) { Group group = new Group(element.getAsJsonObject()); groupDB.put(group.getName(), group); } } else { //noinspection ResultOfMethodCallIgnored file.createNewFile(); JsonObject rootObject = new JsonObject(); rootObject.add("players", new JsonArray()); rootObject.add("groups", new JsonArray()); BufferedWriter bw = new BufferedWriter(new FileWriter(file)); bw.write(GSON.toJson(rootObject)); bw.close(); } }
@Override public JsonElement serialize(RemoteClass src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if (src.getName() != null) { object.addProperty("name", src.getName()); } if (src.getDoc() != null) { object.addProperty("doc", src.getDoc().getDoc()); } if (src.isAbstract()) { object.add("abstract", new JsonPrimitive(true)); } if (src.getExtends() != null) { object.add("extends", context.serialize(src.getExtends())); } if (!src.getConstructors().isEmpty()) { object.add("constructors", context.serialize(src.getConstructors())); } if (!src.getMethods().isEmpty()) { object.add("methods", context.serialize(src.getMethods())); } if (!src.getEvents().isEmpty()) { object.add("events", context.serialize(src.getEvents())); } return object; }
@Override public JsonObject toJson() { final JsonObject json = new JsonObject(); json.add("layer", DAGNetwork.this.byId.get(this.layer).getJson()); if (this.inputNodes.length > 0) json.add("prev0", ((LazyResult) this.inputNodes[0]).toJson()); return json; }
public void saveResponse(String answer) { Log.i(TAG, "saveResponse is called"); final long timestamp = System.currentTimeMillis() / 1000; final String style = this.style; final String surveyGroup = this.surveyGroup; final String question = this.question; final ArrayList<String> options = this.options; Log.i(TAG, "survey answer:" + answer.toString()); // prepare the json object for survey value JsonElement surveyData = new JsonObject(); ((JsonObject) surveyData).addProperty("style", style); ((JsonObject) surveyData).addProperty("surveyGroup", surveyGroup); ((JsonObject) surveyData).addProperty("question", question); JsonElement optionsData = new JsonArray(); for (String option : options) { JsonPrimitive p = new JsonPrimitive(option); ((JsonArray) optionsData).add(p); } ((JsonObject) surveyData).add("options", optionsData); // if the answer is from checkbox style, then we have multiple selections of answers if (style.equals(Survey.CHECKBOX)) { JsonElement surveyAnswers = new JsonArray(); for (String ans : answer.split(",")) { JsonPrimitive p = new JsonPrimitive(ans); ((JsonArray) surveyAnswers).add(p); } ((JsonObject) surveyData).add("answer", surveyAnswers); } else { ((JsonObject) surveyData).addProperty("answer", answer); } ((JsonObject) surveyData).addProperty("probe", SURVEY_HEADER); ((JsonObject) surveyData).add("timezoneOffset", new JsonPrimitive(localOffsetSeconds)); ((JsonObject) surveyData).addProperty("timestamp", System.currentTimeMillis() / 1000); // write to DB Bundle b = new Bundle(); b.putString(NameValueDatabaseService.DATABASE_NAME_KEY, databasename); b.putLong(NameValueDatabaseService.TIMESTAMP_KEY, timestamp); b.putString(NameValueDatabaseService.NAME_KEY, SURVEY_HEADER); b.putString(NameValueDatabaseService.VALUE_KEY, surveyData.toString()); Intent i = new Intent(mContext, NameValueDatabaseService.class); i.setAction(DatabaseService.ACTION_RECORD); i.putExtras(b); mContext.startService(i); // we close the open activity with returned result closeApp(answer); }
public static JsonElement encode(BasicBSONList a) { JsonArray result = new JsonArray(); for (int i = 0; i < a.size(); ++i) { Object o = a.get(i); if (o instanceof DBObject) { result.add(encode((DBObject) o)); } else if (o instanceof BasicBSONObject) { result.add(encode((BasicBSONObject) o)); } else if (o instanceof BasicBSONList) { result.add(encode((BasicBSONList) o)); } else if (o instanceof BasicDBList) { result.add(encode((BasicDBList) o)); } else { // Must be a primitive... if (o instanceof String) { result.add(new JsonPrimitive((String) o)); } else if (o instanceof Number) { result.add(new JsonPrimitive((Number) o)); } else if (o instanceof Boolean) { result.add(new JsonPrimitive((Boolean) o)); } // MongoDB special fields else if (o instanceof ObjectId) { JsonObject oid = new JsonObject(); oid.add("$oid", new JsonPrimitive(((ObjectId) o).toString())); result.add(oid); } else if (o instanceof Date) { JsonObject date = new JsonObject(); date.add("$date", new JsonPrimitive(_format.format((Date) o))); result.add(date); } // Ignore BinaryData, should be serializing that anyway... } } return result; } // TESTED
public void showPrevWinner(Reservation obj) { TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE); String m_deviceId = TelephonyMgr.getDeviceId(); JsonObject bidPrevData = new JsonObject(); // ValueProvider obj1 = new ValueProvider(); JsonObject bidPrevDataBody = new JsonObject(); bidPrevData.addProperty("user_id", "user4"); bidPrevData.addProperty("room_no", obj.getLocation()); bidPrevData.addProperty("start_time", String.valueOf(obj.getStartDate().getTime())); bidPrevData.addProperty("end_time", String.valueOf(obj.getEndDate().getTime())); bidPrevData.addProperty("temperature_f", "0"); // bidData.addProperty("temperature_f", temp_1.getValue(); bidPrevData.addProperty("bid_amount", "0"); bidPrevData.addProperty("timestamp", date.getTime()); bidPrevDataBody.add("bidTemperature", bidPrevData); JsonObject creditData = new JsonObject(); JsonObject creditDataBody = new JsonObject(); creditData.addProperty("user_id", "user4"); creditDataBody.add("UserCredit", creditData); // Gets winning temperature before with bidding is done new GetWinnerHistory(this).execute(bidPrevDataBody.toString()); // // // Gets user credit before the bid is done. new GetCreditController(this).execute(creditDataBody.toString()); // currentWinner.setText(obj1.getPrevWinner()); // // myCoins.setText(obj1.getCredit()); }
@Override public JsonElement serialize( final Counter src, final Type typeOfSrc, final JsonSerializationContext context) { final JsonObject container = new JsonObject(); final JsonObject baseLabels = new JsonObject(); baseLabels.addProperty(Reserved.NAME.label(), src.name); container.add(SERIALIZE_BASE_LABELS, baseLabels); container.addProperty(SERIALIZE_DOCSTRING, src.docstring); final JsonObject metric = new JsonObject(); metric.addProperty("type", "counter"); final JsonArray values = new JsonArray(); for (final Map<String, String> labelSet : src.children.keySet()) { final JsonObject element = new JsonObject(); element.add("labels", context.serialize(labelSet)); final Child vector = src.children.get(labelSet); element.add("value", context.serialize(vector.value.get())); values.add(element); } metric.add("value", values); container.add(SERIALIZE_METRIC, context.serialize(metric)); return container; }
@Override public JsonElement serialize(DataItem src, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if (src.getName() != null) { object.add("name", context.serialize(src.getName())); } if (src.getDoc() != null) { object.addProperty("doc", src.getDoc().getDoc()); } if (src.getType() != null) { object.add("type", context.serialize(src.getType())); } if (src.isOptional()) { object.addProperty("optional", src.isOptional()); if (src.getDefaultValue() != null) { object.add("defaultValue", src.getDefaultValue()); } } return object; }
@Override public JsonElement serialize( WrappedStack wrappedStack, Type type, JsonSerializationContext context) { JsonObject jsonWrappedStack = new JsonObject(); Gson gsonWrappedStack = new Gson(); jsonWrappedStack.addProperty("className", wrappedStack.className); jsonWrappedStack.addProperty("stackSize", wrappedStack.stackSize); if (wrappedStack.wrappedStack instanceof ItemStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, ItemStack.class)); } else if (wrappedStack.wrappedStack instanceof OreStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, OreStack.class)); } else if (wrappedStack.wrappedStack instanceof EnergyStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, EnergyStack.class)); } else if (wrappedStack.wrappedStack instanceof FluidStack) { jsonWrappedStack.add( "wrappedStack", gsonWrappedStack.toJsonTree(wrappedStack.wrappedStack, FluidStack.class)); } return jsonWrappedStack; }
@Override public JsonElement serialize(Versioning src, Type typeOfSrc, JsonSerializationContext context) { JsonObject obj = new JsonObject(); JsonElement type = context.serialize(src.type, VersioningType.class); obj.add("type", type); JsonElement params; switch (src.type) { case EXTERNAL: params = context.serialize(src.params, VersioningExternal.Params.class); break; case SIMPLE: params = context.serialize(src.params, VersioningSimple.Params.class); break; case STAGGERED: params = context.serialize(src.params, VersioningStaggered.Params.class); break; case TRASHCAN: params = context.serialize(src.params, VersioningTrashCan.Params.class); break; case NONE: default: params = null; // context.serialize(src.params, VersioningNone.Params.class); break; } obj.add("params", params); return obj; }
@Override public JsonObject upgrade(JsonObject unitGroup, Map<File, JsonObject> dbSnapshot) throws CouldNotPerformException { String newUnitType = unitTypeMap.get(unitGroup.get(UNIT_TYPE_FIELD).getAsString()); unitGroup.remove(UNIT_TYPE_FIELD); unitGroup.addProperty(UNIT_TYPE_FIELD, newUnitType); JsonArray serviceTemplates = unitGroup.getAsJsonArray(SERVICE_TEMPLATE_FIELD); if (serviceTemplates != null) { JsonArray newServiceTemplates = new JsonArray(); for (JsonElement serviceTemplateElem : serviceTemplates) { JsonObject serviceTemplate = serviceTemplateElem.getAsJsonObject(); String oldServiceType = serviceTemplate.get(SERVICE_TYPE_FIELD).getAsString(); String newServiceType = serviceTypeMap.get(oldServiceType); serviceTemplate.remove(SERVICE_TYPE_FIELD); serviceTemplate.addProperty(TYPE_FIELD, newServiceType); serviceTemplate.addProperty(PATTERN_FIELD, PROVIDER_PATTERN); newServiceTemplates.add(serviceTemplate); if (oldServiceType.endsWith("SERVICE")) { JsonObject operationServiceTemplate = new JsonObject(); operationServiceTemplate.addProperty(TYPE_FIELD, newServiceType); operationServiceTemplate.addProperty(PATTERN_FIELD, OPERATION_PATTERN); operationServiceTemplate.add(META_CONFIG_FIELD, serviceTemplate.get(META_CONFIG_FIELD)); newServiceTemplates.add(operationServiceTemplate); } } unitGroup.remove(SERVICE_TEMPLATE_FIELD); unitGroup.add(SERVICE_TEMPLATE_FIELD, newServiceTemplates); } return unitGroup; }
@Override public JsonElement serialize(Operator op, Type type, JsonSerializationContext jsc) { JsonObject jsonObject = new JsonObject(); jsonObject.addProperty(PlanExpressionConstants.CONTAINERNAME, op.containerName); jsonObject.addProperty(PlanExpressionConstants.OPERATOR, op.operator); jsonObject.addProperty(PlanExpressionConstants.OPERATORNAME, op.operatorName); if (op.queryString != null) { jsonObject.addProperty(PlanExpressionConstants.QUERYSTRING, op.queryString); } if (op.locations != null) { JsonParser parser = new JsonParser(); JsonArray locations = new JsonArray(); for (URL url : op.locations) { locations.add(parser.parse(url.toString())); } jsonObject.add(PlanExpressionConstants.LOCATIONS, locations); } if (op.paramList != null) { JsonParser parser = new JsonParser(); JsonArray params = new JsonArray(); for (Parameter param : op.paramList) { JsonArray p = new JsonArray(); p.add(parser.parse(param.name)); p.add(parser.parse(param.value)); params.add(p); } jsonObject.add(PlanExpressionConstants.PARAMETERS, params); } return jsonObject; }
@Override public JsonElement serialize(Crowd crowd, Type typeOfSrc, JsonSerializationContext context) { JsonObject object = new JsonObject(); if (crowd.getId() == null || crowd.getId().isEmpty()) { object.addProperty("_id", "-1"); } else { object.addProperty("_id", crowd.getId()); } object.addProperty("name", crowd.getName()); object.addProperty("owner", crowd.getOwner()); if (crowd.getMembers() == null || crowd.getMembers().isEmpty()) { object.add("members", JsonNull.INSTANCE); } else { JsonArray members = new JsonArray(); for (MemberId memberId : crowd.getMembers()) { members.add(new JsonPrimitive(memberId.getId())); object.add("members", members); } } Log.i("CrowdSerializer", "Serialized: " + object.toString()); return object; }
@Override public JsonElement serialize(NPermissionManager src, Type t, JsonSerializationContext context) { JsonObject obj = new JsonObject(); try { JsonArray roles = new JsonArray(); for (Entry<Role, HashSet<NPermission>> entry : src.getRankPerms().entrySet()) { StringBuilder ret = new StringBuilder(); ret.append(entry.getKey().name()); for (NPermission perm : entry.getValue()) { ret.append("," + perm.toString()); } roles.add(new JsonPrimitive(ret.toString())); } obj.add(ROLES, roles); JsonArray players = new JsonArray(); for (Entry<String, HashMap<NPermission, Boolean>> entry : src.getPlayerPerms().entrySet()) { StringBuilder ret = new StringBuilder(); ret.append(entry.getKey()); for (Entry<NPermission, Boolean> e : entry.getValue().entrySet()) { ret.append("," + e.getKey().toString() + ":" + ((e.getValue()) ? "t" : "f")); } players.add(new JsonPrimitive(ret.toString())); } obj.add(PLAYERS, players); return obj; } catch (Exception ex) { ex.printStackTrace(); SwornNations.get() .log(Level.WARNING, "Error encountered while serializing NPermissionManager."); return obj; } }
@Override public JsonElement serialize(MoveStrategy src, Type typeOfSrc, JsonSerializationContext context) { JsonObject result = new JsonObject(); result.add("type", new JsonPrimitive(src.getClass().getSimpleName())); result.add("properties", context.serialize(src, src.getClass())); return result; }
public static JsonObject mergeJsonFiles(JsonObject target, String... filenames) throws IOException { if (target == null) { target = new JsonObject(); } for (String filename : filenames) { String url = Config.CLOUD_STORAGE_BASE_URL + filename; JsonObject obj = fetchJsonFromPublicURL(url); if (obj == null) { throw new FileNotFoundException(url); } else { for (Entry<String, JsonElement> entry : obj.entrySet()) { if (entry.getValue().isJsonArray()) { // tries to merge an array with the existing one, if it's the case: JsonArray existing = target.getAsJsonArray(entry.getKey()); if (existing == null) { existing = new JsonArray(); target.add(entry.getKey(), existing); } existing.addAll(entry.getValue().getAsJsonArray()); } else { target.add(entry.getKey(), entry.getValue()); } } } } return target; }
@Override public JsonElement serialize( CreatureTypeSaveObject src, Type typeOfSrc, JsonSerializationContext context) { JsonObject endObject = new JsonObject(); endObject.addProperty(FILE_VERSION_KEY, FILE_VERSION); JsonObject types = new JsonObject(); for (CreatureTypeBuilder type : src.types.get().values()) { JsonObject entry = new JsonObject(); entry.addProperty(SPAWN_RATE_KEY, type.spawnRate); entry.addProperty(MAX_CREATURE_KEY, type.maxNumberOfCreature); entry.addProperty(CHUNK_CHANCE_KEY, type.getChunkSpawnChance()); entry.addProperty(SPAWN_MEDIUM_KEY, type.getRawSpawnMedium()); entry.addProperty(ITER_PER_CHUNK, type.getIterationsPerChunk()); entry.addProperty(ITER_PER_PACK, type.getIterationsPerPack()); entry.addProperty(OPTIONAL_PARAM_KEY, type.getSpawnExpression()); entry.addProperty(DEFAULT_BIOME_CAP_KEY, type.getDefaultBiomeCap()); JsonObject biomeCaps = new JsonObject(); for (Entry<String, Integer> capEntry : type.getBiomeCaps().entrySet()) { biomeCaps.addProperty(capEntry.getKey(), capEntry.getValue()); } entry.add(MAPPING_TO_CAP, biomeCaps); types.add(type.typeID, entry); } endObject.add(TYPE_KEY, types); return endObject; }
private static InputStream generateSoundsJSON() throws IOException { OpenSecurity.logger.info( Minecraft.getMinecraft().mcDataDir + "\\mods\\OpenSecurity\\sounds\\alarms\\"); JsonObject root = new JsonObject(); for (Map.Entry<String, String> entry : sound_map.entrySet()) { JsonObject event = new JsonObject(); event.addProperty("category", "master"); // put under the "record" category for sound options JsonArray sounds = new JsonArray(); // array of sounds (will only ever be one) JsonObject sound = new JsonObject(); // sound object (instead of primitive to use 'stream' flag) sound.addProperty( "name", new File(".") + "\\mods\\OpenSecurity\\sounds\\alarms\\" + entry.getValue().substring(0, entry.getValue().lastIndexOf('.'))); // path to file sound.addProperty("stream", false); // prevents lag for large files sounds.add(sound); event.add("sounds", sounds); root.add( entry.getValue().substring(0, entry.getValue().lastIndexOf('.')), event); // event name (same as name sent to ItemCustomRecord) } // System.out.println(new Gson().toJson(root)); return new ByteArrayInputStream(new Gson().toJson(root).getBytes()); }
/** * Gson invokes this call-back method during serialization when it encounters a field of the * specified type. * * <p> * * <p>In the implementation of this call-back method, you should consider invoking {@link * com.google.gson.JsonSerializationContext#serialize(Object, java.lang.reflect.Type)} method to * create JsonElements for any non-trivial field of the {@code wrappedStack} object. However, you * should never invoke it on the {@code wrappedStack} object itself since that will cause an * infinite loop (Gson will call your call-back method again). * * @param wrappedStack the object that needs to be converted to Json. * @param typeOfSrc the actual type (fully genericized version) of the source object. * @param context * @return a JsonElement corresponding to the specified object. */ @Override public JsonElement serialize( WrappedStack wrappedStack, Type typeOfSrc, JsonSerializationContext context) { JsonObject jsonWrappedStack = new JsonObject(); Gson gson = new Gson(); jsonWrappedStack.addProperty("type", wrappedStack.objectType); jsonWrappedStack.addProperty("stackSize", wrappedStack.stackSize); if (wrappedStack.wrappedStack instanceof ItemStack) { JsonItemStack jsonItemStack = new JsonItemStack(); jsonItemStack.itemName = Item.itemRegistry.getNameForObject(((ItemStack) wrappedStack.wrappedStack).getItem()); jsonItemStack.itemDamage = ((ItemStack) wrappedStack.wrappedStack).getItemDamage(); if (((ItemStack) wrappedStack.wrappedStack).stackTagCompound != null) { jsonItemStack.itemNBTTagCompound = ((ItemStack) wrappedStack.wrappedStack).stackTagCompound; } jsonWrappedStack.add( "objectData", JsonItemStack.jsonSerializer.toJsonTree(jsonItemStack, JsonItemStack.class)); } else if (wrappedStack.wrappedStack instanceof OreStack) { jsonWrappedStack.add( "objectData", gson.toJsonTree(wrappedStack.wrappedStack, OreStack.class)); } else if (wrappedStack.wrappedStack instanceof FluidStack) { JsonFluidStack jsonFluidStack = new JsonFluidStack((FluidStack) wrappedStack.wrappedStack); jsonWrappedStack.add( "objectData", JsonFluidStack.jsonSerializer.toJsonTree(jsonFluidStack, JsonFluidStack.class)); } return jsonWrappedStack; }
public static String a(Map var0) { JsonObject var1 = new JsonObject(); Iterator var2 = var0.entrySet().iterator(); while (var2.hasNext()) { Entry var3 = (Entry) var2.next(); if (((class_nf) var3.getValue()).b() != null) { JsonObject var4 = new JsonObject(); var4.addProperty("value", Integer.valueOf(((class_nf) var3.getValue()).a())); try { var4.add("progress", ((class_nf) var3.getValue()).b().a()); } catch (Throwable var6) { b.warn( "Couldn\'t save statistic " + ((class_nd) var3.getKey()).e() + ": error serializing progress", var6); } var1.add(((class_nd) var3.getKey()).e, var4); } else { var1.addProperty( ((class_nd) var3.getKey()).e, Integer.valueOf(((class_nf) var3.getValue()).a())); } } return var1.toString(); }
@Override public JsonElement serialize( OutputDataRaw cellRaw, Type typeOfSrc, JsonSerializationContext context) { final JsonObject jsonObject = new JsonObject(); if (cellRaw.png != null) { jsonObject.addProperty("image/png", cellRaw.png); } if (cellRaw.html != null) { final JsonElement html = gson.toJsonTree(cellRaw.html); jsonObject.add("text/html", html); } if (cellRaw.svg != null) { final JsonElement svg = gson.toJsonTree(cellRaw.svg); jsonObject.add("image/svg+xml", svg); } if (cellRaw.jpeg != null) { final JsonElement jpeg = gson.toJsonTree(cellRaw.jpeg); jsonObject.add("image/jpeg", jpeg); } if (cellRaw.latex != null) { final JsonElement latex = gson.toJsonTree(cellRaw.latex); jsonObject.add("text/latex", latex); } if (cellRaw.text != null) { final JsonElement text = gson.toJsonTree(cellRaw.text); jsonObject.add("text/plain", text); } return jsonObject; }
public String create() { try { JsonObject gistJson = new JsonObject(); gistJson.addProperty("description", this.getDescription()); gistJson.addProperty("public", this.isPublic()); JsonObject filesJson = new JsonObject(); for (int i = 0; i < getFiles().length; i++) { GistFile gistFile = getFiles()[i]; JsonObject file = new JsonObject(); file.addProperty("content", gistFile.getContent()); String name = gistFile.getFileName(); filesJson.add( (name == null || name.isEmpty() ? "" : name + "-") + date.replace(' ', '_'), file); } gistJson.add("files", filesJson); HttpResponse<JsonNode> response = Unirest.post(GitHub.GISTS_API_URL) .header( "authorization", "token " + Nexus.getInstance().getGitHubConfig().getNexusGitHubApiKey()) .header("accept", "application/json") .header("content-type", "application/json; charset=utf-8") .body(gistJson.toString()) .asJson(); return response.getBody().getObject().getString("html_url"); } catch (UnirestException e) { throw new GistException("Failed to Gist!", e); } }
public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); jsonObject.add("classElement", classElement.toJson()); if (displayName != null) { jsonObject.addProperty("displayName", displayName); } if (memberElement != null) { jsonObject.add("memberElement", memberElement.toJson()); } if (superclass != null) { jsonObject.addProperty("superclass", superclass); } JsonArray jsonArrayInterfaces = new JsonArray(); for (int elt : interfaces) { jsonArrayInterfaces.add(new JsonPrimitive(elt)); } jsonObject.add("interfaces", jsonArrayInterfaces); JsonArray jsonArrayMixins = new JsonArray(); for (int elt : mixins) { jsonArrayMixins.add(new JsonPrimitive(elt)); } jsonObject.add("mixins", jsonArrayMixins); JsonArray jsonArraySubclasses = new JsonArray(); for (int elt : subclasses) { jsonArraySubclasses.add(new JsonPrimitive(elt)); } jsonObject.add("subclasses", jsonArraySubclasses); return jsonObject; }
/** * return Json of all Transaction * * @return Json of all Transaction */ public JsonArray toJSON(ArrayList<Transaction> result) { JsonArray resultArray = new JsonArray(); for (int i = 0; i < result.size(); i++) { // add properties JsonObject properties = new JsonObject(); properties.addProperty("REC_NO", result.get(i).get_rec_no()); properties.addProperty("PROJECT_NAME", result.get(i).get_project_name()); properties.addProperty("ADDRESS", result.get(i).get_address()); properties.addProperty("NO_OF_UNITS", result.get(i).get_no_of_units()); properties.addProperty("AREA_SQM", result.get(i).get_area_sqm()); properties.addProperty("TYPE_OF_AREA", result.get(i).get_type_of_area()); properties.addProperty("TRANSACTED_PRICE", result.get(i).get_transacted_price()); properties.addProperty("UNIT_PRICE_PSM", result.get(i).get_unit_price_psm()); properties.addProperty("UNIT_PRICE_PSF", result.get(i).get_unit_price_psf()); properties.addProperty("CONTRACT_DATE", result.get(i).get_contract_date()); properties.addProperty("PROPERTY_TYPE", result.get(i).get_property_type()); properties.addProperty("TENURE", result.get(i).get_tenure()); properties.addProperty("COMPLETION_DATE", result.get(i).get_completion_date()); properties.addProperty("TYPE_OF_SALE", result.get(i).get_type_of_sale()); properties.addProperty( "PURCHASER_ADDRESS_INDICATOR", result.get(i).get_purchaser_address_indicator()); properties.addProperty("POSTAL_DISTRICT", result.get(i).get_postal_district()); properties.addProperty("POSTAL_SECTOR", result.get(i).get_postal_sector()); properties.addProperty("POSTAL_CODE", result.get(i).get_postal_code()); properties.addProperty("PLANNING_REGION", result.get(i).get_planning_region()); properties.addProperty("PLANNING_AREA", result.get(i).get_planning_area()); properties.addProperty("X", result.get(i).get_x()); properties.addProperty("Y", result.get(i).get_y()); // add coordinates JsonArray coordinates = new JsonArray(); JsonObject lat = new JsonObject(); JsonObject lon = new JsonObject(); lat.addProperty("lat", result.get(i).get_x()); lon.addProperty("lon", result.get(i).get_y()); coordinates.add(lat); coordinates.add(lon); // add geometry JsonObject geometry = new JsonObject(); geometry.addProperty("type", "Point"); geometry.add("coordinates", coordinates); // add everything into one record JsonObject record = new JsonObject(); record.addProperty("type", "Feature"); record.addProperty("popupContent", "Hello!"); record.add("properties", properties); record.add("geometry", geometry); // append to resultArray resultArray.add(record); } return resultArray; }
/** * Static implementation-independent GSON serializer. Call this from {@link #toGson} to avoid * subclassing issues with inner message types. */ public static JsonElement toGsonHelper(WaveletDiff message, RawStringData raw, Gson gson) { JsonObject json = new JsonObject(); json.add("1", new JsonPrimitive(message.getWaveletId())); if (message.hasSnapshot()) { json.add("2", WaveletDiffSnapshotGsonImpl.toGsonHelper(message.getSnapshot(), raw, gson)); } return json; }
@Override public void onDataReceived(IJsonObject probeConfig, IJsonObject data) { JsonObject record = new JsonObject(); record.add("name", probeConfig.get(RuntimeTypeAdapterFactory.TYPE)); record.add("value", data); handler.obtainMessage(DATA, record).sendToTarget(); }
@Override public JsonElement serialize(Dimension src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) return null; JsonObject o = new JsonObject(); o.add("width", new JsonPrimitive(src.width)); o.add("height", new JsonPrimitive(src.height)); return o; }
protected void serialize( @Nonnull JsonObject object, @Nonnull BaseComponent component, @Nonnull JsonSerializationContext context) { boolean first = false; if (ComponentSerializer.serializedComponents.get() == null) { first = true; ComponentSerializer.serializedComponents.set(new HashSet<BaseComponent>()); } try { Checks.check( !ComponentSerializer.serializedComponents.get().contains(component), "Component loop"); ComponentSerializer.serializedComponents.get().add(component); if (component.getColorRaw() != null) { object.addProperty("color", component.getColorRaw().getName()); } if (component.isBoldRaw() != null) { object.addProperty("bold", component.isBoldRaw()); } if (component.isItalicRaw() != null) { object.addProperty("italic", component.isItalicRaw()); } if (component.isUnderlinedRaw() != null) { object.addProperty("underlined", component.isUnderlinedRaw()); } if (component.isStrikethroughRaw() != null) { object.addProperty("strikethrough", component.isStrikethroughRaw()); } if (component.isObfuscatedRaw() != null) { object.addProperty("obfuscated", component.isObfuscatedRaw()); } if (component.getExtra() != null) { object.add("extra", context.serialize(component.getExtra())); } // Events if (component.getClickEvent() != null) { JsonObject clickEvent = new JsonObject(); clickEvent.addProperty( "action", component.getClickEvent().getAction().toString().toLowerCase()); clickEvent.addProperty("value", component.getClickEvent().getValue()); object.add("clickEvent", clickEvent); } if (component.getHoverEvent() != null) { JsonObject hoverEvent = new JsonObject(); hoverEvent.addProperty( "action", component.getHoverEvent().getAction().toString().toLowerCase()); hoverEvent.add("value", context.serialize(component.getHoverEvent().getValue())); object.add("hoverEvent", hoverEvent); } } finally { ComponentSerializer.serializedComponents.get().remove(component); if (first) { ComponentSerializer.serializedComponents.set(null); } } }