Example usage for com.google.gson JsonObject addProperty

List of usage examples for com.google.gson JsonObject addProperty

Introduction

In this page you can find the example usage for com.google.gson JsonObject addProperty.

Prototype

public void addProperty(String property, Character value) 

Source Link

Document

Convenience method to add a char member.

Usage

From source file:club.jmint.mifty.service.DemoServiceImpl.java

License:Apache License

/**
 * @param {"echo":"I am a DEMO","name":"DemoService"}
 *///  w ww  . j  a  va2  s .com
public String demoSay(String params, boolean isEncrypt) throws TException {
    //parse parameters and verify signature
    CrossLog.logger.debug("echo: " + params);
    JsonObject ip;
    try {
        ip = parseInputParams(params, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }

    //validate parameters on business side
    String name, echo;
    try {
        name = getParamAsString(ip, "name");
        echo = getParamAsString(ip, "echo");
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }

    //do more checks here if you need.

    //do your business logics
    System.out.println("name: " + name);
    System.out.println("echo: " + echo);
    CrossLog.logger.info("\nname: " + name + "\nsay: " + echo);

    String sentence = "Hi, " + name + " ," + echo;
    //do more things here.

    //build response parameters
    JsonObject op = new JsonObject();
    op.addProperty("sentence", sentence);
    String output = null;
    try {
        output = buildOutputParams(op, isEncrypt);
    } catch (CrossException ce) {
        return buildOutputByCrossException(ce);
    }
    CrossLog.logger.debug("sayHello: " + output);
    return output;
}

From source file:cmput301.f13t01.elasticsearch.InterfaceAdapter.java

License:GNU General Public License

/**
 * This allows for the serialization of objects that use an interface to be
 * wrapped and retain memory of its type.
 * //www .jav a 2 s  .co  m
 * @return Returns the JsonElement to be used by Gson
 */
public JsonElement serialize(T object, Type interfaceType, JsonSerializationContext context) {
    final JsonObject wrapper = new JsonObject();
    wrapper.addProperty("type", object.getClass().getName());
    wrapper.add("data", context.serialize(object));
    return wrapper;
}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private boolean uploadAuthInfo() {
    SharedPreferences prefs = getSharedPreferences(Contants.SHARED_NAME, MODE_PRIVATE);

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("UserId", prefs.getString("UserId", ""));

    String userName = name.getText().toString();
    if (TextUtils.isEmpty(userName))
        return false;
    jsonObject.addProperty("UserName", userName);

    RadioButton radioButton = (RadioButton) findViewById(sexGroup.getCheckedRadioButtonId());
    if (radioButton == null)
        return false;
    String sex = radioButton.getText().toString();
    if (TextUtils.isEmpty(sex))
        return false;
    jsonObject.addProperty("Sex", sex);

    String idNumber = cardNo.getText().toString();
    if (TextUtils.isEmpty(idNumber))
        return false;
    jsonObject.addProperty("IDNumber", idNumber);

    String phoneStr = phone.getText().toString();
    if (TextUtils.isEmpty(phoneStr))
        return false;
    jsonObject.addProperty("Phone", phoneStr);

    String driverId = drivingLicense.getText().toString();
    if (TextUtils.isEmpty(driverId))
        return false;
    jsonObject.addProperty("DriverId", driverId);

    final String vehicleNoSelect = carNumberSelect.getText().toString();
    final String vehicleNo = carNumber.getText().toString();
    if (TextUtils.isEmpty(vehicleNoSelect) || TextUtils.isEmpty(vehicleNo))
        return false;
    jsonObject.addProperty("VehicleNo", vehicleNoSelect + vehicleNo);

    String travelCard = roadTransportPermit.getText().toString();
    if (TextUtils.isEmpty(travelCard))
        return false;
    jsonObject.addProperty("TravelCard", travelCard);

    String gpsNo = gpsSystemNo.getText().toString();
    if (TextUtils.isEmpty(gpsNo))
        return false;
    jsonObject.addProperty("GpsNo", gpsNo);

    if (VehType == -1)
        return false;
    jsonObject.addProperty("VehType", VehType);

    String phone1 = urgentContact.getText().toString();
    if (TextUtils.isEmpty(phone1))
        return false;
    jsonObject.addProperty("Phone1", phone1);

    String width = vehicleWidth.getText().toString();
    if (TextUtils.isEmpty(width))
        return false;
    jsonObject.addProperty("Width", width);

    String height = vehicleHeight.getText().toString();
    if (TextUtils.isEmpty(height))
        return false;
    jsonObject.addProperty("Height", height);

    String length = vehicleLength.getText().toString();
    if (TextUtils.isEmpty(length))
        return false;
    jsonObject.addProperty("Length", length);

    String tons = vehicleMaxCapacity.getText().toString();
    if (TextUtils.isEmpty(tons))
        return false;
    jsonObject.addProperty("Tons", tons);

    String checkCode = phoneVerify.getText().toString();
    if (TextUtils.isEmpty(checkCode))
        return false;
    jsonObject.addProperty("CheckCode", checkCode);

    if (isGetVerify) {
        Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());
        HttpUtil.doPost(AuthFirstActivity.this, Contants.url_TransporterVehicleCheck1, "VehicleCheck1", map,
                new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                        VolleyInterface.mErrorListener) {
                    @Override/*www  .  j  a  v  a  2  s.  c o m*/
                    public void onSuccess(JsonElement result) {
                        Intent intent = new Intent(AuthFirstActivity.this, AuthSecondActivity.class);
                        //intent.putExtra("VehicleNo", vehicleNoSelect + vehicleNo);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onError(VolleyError error) {
                    }

                    @Override
                    public void onStateError(int sta, String msg) {
                        if (!TextUtils.isEmpty(msg)) {
                            showShortToastByString(msg);
                        }
                    }
                });

        return true;
    } else {
        showShortToastByString("???");
        return false;
    }
}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private void getAuthInfo() {
    SharedPreferences prefs = getSharedPreferences(Contants.SHARED_NAME, MODE_PRIVATE);

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("UserID", prefs.getString("UserId", ""));

    Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());
    HttpUtil.doPost(AuthFirstActivity.this, Contants.url_TransporterGetVehicleCheck1, "GetVehicleCheck1", map,
            new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override/*from   w  w w.j  a  v  a2 s .c om*/
                public void onSuccess(JsonElement result) {
                    Gson gson = new Gson();
                    VehicleAuth1 vehicleAuth = gson.fromJson(result, VehicleAuth1.class);
                    setAuthInfo(vehicleAuth);
                }

                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:cn.com.caronwer.activity.AuthFirstActivity.java

private void getCheckCode() {
    String account = urgentContact.getText().toString();
    if (account.isEmpty()) {
        showShortToastByString("???");
        return;// ww  w .  jav a  2s .  co m
    }
    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("Tel", account);
    Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());

    HttpUtil.doPost(AuthFirstActivity.this, Contants.url_obtainCheckCode, "obtainCheckCode", map,
            new VolleyInterface(AuthFirstActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override
                public void onSuccess(JsonElement result) {
                    isGetVerify = true;
                    Toast.makeText(AuthFirstActivity.this, "????", Toast.LENGTH_SHORT).show();

                    Message message = handler.obtainMessage(1); // Message
                    message.arg1 = 120;
                    handler.sendMessageDelayed(message, 1000); //
                }

                @Override
                public void onError(VolleyError error) {
                    Toast.makeText(AuthFirstActivity.this, "?", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:cn.com.caronwer.activity.AuthSecondActivity.java

private void getAuthInfo() {
    SharedPreferences prefs = getSharedPreferences(Contants.SHARED_NAME, MODE_PRIVATE);

    JsonObject jsonObject = new JsonObject();
    jsonObject.addProperty("UserID", prefs.getString("UserId", ""));

    Map<String, String> map = EncryptUtil.encryptDES(jsonObject.toString());
    HttpUtil.doPost(AuthSecondActivity.this, Contants.url_TransporterGetVehicleCheck2, "GetVehicleCheck2", map,
            new VolleyInterface(AuthSecondActivity.this, VolleyInterface.mListener,
                    VolleyInterface.mErrorListener) {
                @Override//from  w w w. j  av a 2  s.  com
                public void onSuccess(JsonElement result) {
                    Gson gson = new Gson();
                    VehicleAuth2 vehicleAuth = gson.fromJson(result, VehicleAuth2.class);
                    setAuthInfo(vehicleAuth);
                }

                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onStateError(int sta, String msg) {
                    if (!TextUtils.isEmpty(msg)) {
                        showShortToastByString(msg);
                    }
                }
            });
}

From source file:co.aikar.timings.TimingsExport.java

License:MIT License

/**
 * Builds a JSON timings report and sends it to Aikar's viewer
 *
 * @param sender Sender that issued the command
 *//*from  w  w w  . jav a 2  s .c  o m*/
public static void reportTimings(CommandSender sender) {
    JsonObject out = new JsonObject();
    out.addProperty("version", Server.getInstance().getVersion());
    out.addProperty("maxplayers", Server.getInstance().getMaxPlayers());
    out.addProperty("start", TimingsManager.timingStart / 1000);
    out.addProperty("end", System.currentTimeMillis() / 1000);
    out.addProperty("sampletime", (System.currentTimeMillis() - TimingsManager.timingStart) / 1000);

    if (!Timings.isPrivacy()) {
        out.addProperty("server", Server.getInstance().getName());
        out.addProperty("motd", Server.getInstance().getMotd());
        out.addProperty("online-mode", false); //In MCPE we have permanent offline mode.
        out.addProperty("icon", ""); //"data:image/png;base64,"
    }

    final Runtime runtime = Runtime.getRuntime();
    RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean();

    JsonObject system = new JsonObject();
    system.addProperty("timingcost", getCost());
    system.addProperty("name", System.getProperty("os.name"));
    system.addProperty("version", System.getProperty("os.version"));
    system.addProperty("jvmversion", System.getProperty("java.version"));
    system.addProperty("arch", System.getProperty("os.arch"));
    system.addProperty("maxmem", runtime.maxMemory());
    system.addProperty("cpu", runtime.availableProcessors());
    system.addProperty("runtime", ManagementFactory.getRuntimeMXBean().getUptime());
    system.addProperty("flags", String.join(" ", runtimeBean.getInputArguments()));
    system.add("gc",
            JsonUtil.mapToObject(ManagementFactory.getGarbageCollectorMXBeans(),
                    (input) -> new JsonUtil.JSONPair(input.getName(),
                            JsonUtil.toArray(input.getCollectionCount(), input.getCollectionTime()))));
    out.add("system", system);

    TimingsHistory[] history = HISTORY.toArray(new TimingsHistory[HISTORY.size() + 1]);
    history[HISTORY.size()] = new TimingsHistory(); //Current snapshot

    JsonObject timings = new JsonObject();
    for (TimingIdentifier.TimingGroup group : TimingIdentifier.GROUP_MAP.values()) {
        for (Timing id : group.timings.stream().toArray(Timing[]::new)) {
            if (!id.timed && !id.isSpecial()) {
                continue;
            }

            timings.add(String.valueOf(id.id), JsonUtil.toArray(group.id, id.name));
        }
    }

    JsonObject idmap = new JsonObject();
    idmap.add("groups", JsonUtil.mapToObject(TimingIdentifier.GROUP_MAP.values(),
            (group) -> new JsonUtil.JSONPair(group.id, group.name)));
    idmap.add("handlers", timings);
    idmap.add("worlds", JsonUtil.mapToObject(TimingsHistory.levelMap.entrySet(),
            (entry) -> new JsonUtil.JSONPair(entry.getValue(), entry.getKey())));
    idmap.add("tileentity", JsonUtil.mapToObject(TimingsHistory.blockEntityMap.entrySet(),
            (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue())));
    idmap.add("entity", JsonUtil.mapToObject(TimingsHistory.entityMap.entrySet(),
            (entry) -> new JsonUtil.JSONPair(entry.getKey(), entry.getValue())));
    out.add("idmap", idmap);

    //Information about loaded plugins
    out.add("plugins",
            JsonUtil.mapToObject(Server.getInstance().getPluginManager().getPlugins().values(), (plugin) -> {
                JsonObject jsonPlugin = new JsonObject();
                jsonPlugin.addProperty("version", plugin.getDescription().getVersion());
                jsonPlugin.addProperty("description", plugin.getDescription().getDescription());// Sounds legit
                jsonPlugin.addProperty("website", plugin.getDescription().getWebsite());
                jsonPlugin.addProperty("authors", String.join(", ", plugin.getDescription().getAuthors()));
                return new JsonUtil.JSONPair(plugin.getName(), jsonPlugin);
            }));

    //Information on the users Config
    JsonObject config = new JsonObject();
    if (!Timings.getIgnoredConfigSections().contains("all")) {
        JsonObject nukkit = JsonUtil.toObject(Server.getInstance().getConfig().getRootSection());
        Timings.getIgnoredConfigSections().forEach(nukkit::remove);
        config.add("nukkit", nukkit);
    } else {
        config.add("nukkit", null);
    }
    out.add("config", config);

    new TimingsExport(sender, out, history).start();
}

From source file:co.aikar.timings.TimingsHistory.java

License:MIT License

JsonObject export() {
    JsonObject json = new JsonObject();
    json.addProperty("s", this.startTime);
    json.addProperty("e", this.endTime);
    json.addProperty("tk", this.totalTicks);
    json.addProperty("tm", this.totalTime);
    json.add("w", this.levels);
    json.add("h", JsonUtil.mapToArray(this.entries, (entry) -> {
        if (entry.data.count == 0) {
            return null;
        }/*from  w w  w .  j a v  a  2 s .  co m*/
        return entry.export();
    }));
    json.add("mp", JsonUtil.mapToArray(this.minuteReports, MinuteReport::export));
    return json;
}

From source file:co.aurasphere.botmill.kik.util.json.LowerCaseTypeAdapterFactory.java

License:Open Source License

public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    final TypeAdapter<JsonElement> elementAdapter = gson.getAdapter(JsonElement.class);
    final TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);

    return new TypeAdapter<T>() {

        @Override/*from  w ww  .  ja  v  a2 s .  co m*/
        public T read(JsonReader in) throws IOException {
            JsonElement tree = elementAdapter.read(in);
            afterRead(tree);
            return delegate.fromJsonTree(tree);
        }

        @Override
        public void write(JsonWriter out, T value) throws IOException {
            JsonElement tree = delegate.toJsonTree(value);
            beforeWrite(value, tree);
            elementAdapter.write(out, tree);
        }

        protected void beforeWrite(T source, JsonElement toSerialize) {
        }

        protected void afterRead(JsonElement deserialized) {
            if (deserialized instanceof JsonObject) {
                JsonObject jsonObject = ((JsonObject) deserialized);
                Set<Map.Entry<String, JsonElement>> entrySet = jsonObject.entrySet();
                for (Map.Entry<String, JsonElement> entry : entrySet) {
                    if (entry.getValue() instanceof JsonElement) {
                        if (entry.getKey().equalsIgnoreCase("type")) {
                            String val = jsonObject.get(entry.getKey()).toString();
                            jsonObject.addProperty(entry.getKey(), val.toLowerCase());
                        }
                    } else {
                        afterRead(entry.getValue());
                    }
                }
            }
        }
    };
}

From source file:co.cask.cdap.api.dataset.lib.ConditionCodec.java

License:Apache License

@Override
public JsonElement serialize(PartitionFilter.Condition condition, Type type,
        JsonSerializationContext jsonSerializationContext) {
    JsonObject jsonObj = new JsonObject();
    jsonObj.addProperty("fieldName", condition.getFieldName());
    jsonObj.add("lower", serializeComparable(condition.getLower(), jsonSerializationContext));
    jsonObj.add("upper", serializeComparable(condition.getUpper(), jsonSerializationContext));
    jsonObj.addProperty("isSingleValue", condition.isSingleValue());
    return jsonObj;
}