Example usage for com.google.gson JsonObject add

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

Introduction

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

Prototype

public void add(String property, JsonElement value) 

Source Link

Document

Adds a member, which is a name-value pair, to self.

Usage

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public void addBranchToJson(String newBranch, JsonObject json, String value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]),
                    value);/*  w w w.j av a2  s. co m*/
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.addProperty(newNodes[0], value);
    }
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public void addBranchToJson(String newBranch, JsonObject json, JsonObject value) {
    String[] newNodes = newBranch.split("\\.");
    JsonObject temp;// = new JsonObject();

    if (newNodes.length > 1) {
        if (json.has(newNodes[0])) {
            addBranchToJson(newBranch.substring(newNodes[0].length() + 1), json.getAsJsonObject(newNodes[0]),
                    value);//from  w w w .  j  av a2s . c o  m
        } else {
            temp = createJsonFromString(newBranch.substring(newNodes[0].length() + 1), value);
            json.add(newNodes[0], temp);
        }
    } else {
        json.add(newNodes[0], value);
    }
}

From source file:br.unicamp.cst.bindings.soar.SOARPlugin.java

License:Open Source License

public JsonObject fromBeanToJson(Object bean) {
    JsonObject json = new JsonObject();
    Class type = bean.getClass();

    json.add(type.getName(), new JsonObject());
    try {//  www .j  av a 2  s.  c  om
        Object obj = type.newInstance();
        type.cast(obj);

        for (Field field : type.getFields()) {
            json.addProperty(field.getName(), field.get(bean).toString());
        }
    } catch (Exception e) {
    }

    return json;
}

From source file:brand.GetBrandMaster.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w  ww .j av  a  2s.  co  m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final DBHelper helper = DBHelper.GetDBHelper();
    final Connection dataConnection = helper.getConnMpAdmin();
    final JsonObject jResultObj = new JsonObject();
    if (dataConnection != null) {
        try {
            String sql = "select BRAND_CD,BRAND_NAME,USER_ID from BRANDMST";
            PreparedStatement pstLocal = dataConnection.prepareStatement(sql);
            ResultSet rsLocal = pstLocal.executeQuery();
            JsonArray array = new JsonArray();
            while (rsLocal.next()) {
                JsonObject object = new JsonObject();
                object.addProperty("BRAND_CD", rsLocal.getString("BRAND_CD"));
                object.addProperty("BRAND_NAME", rsLocal.getString("BRAND_NAME"));
                object.addProperty("USER_ID", rsLocal.getInt("USER_ID"));
                array.add(object);
            }
            jResultObj.addProperty("result", 1);
            jResultObj.addProperty("Cause", "success");
            jResultObj.add("data", array);
        } catch (SQLNonTransientConnectionException ex1) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", "Server is down");
        } catch (SQLException ex) {
            jResultObj.addProperty("result", -1);
            jResultObj.addProperty("Cause", ex.getMessage());
        }
    }
    response.getWriter().print(jResultObj);
}

From source file:buri.ddmsence.ddms.security.ntk.Access.java

License:Open Source License

/**
 * An extra layer is added around the individualList and groupList, to make the output consistent with the profileList.
 * /*from w w w  . j av a 2 s.  com*/
 * @see AbstractBaseComponent#getJSONObject()
 */
public JsonObject getJSONObject() {
    JsonObject object = new JsonObject();

    if (!getIndividuals().isEmpty()) {
        JsonObject individualList = new JsonObject();
        individualList.add("individual", Util.getJSONArray(getIndividuals()));
        addJson(object, "individualList", individualList);
    }

    if (!getGroups().isEmpty()) {
        JsonObject groupList = new JsonObject();
        groupList.add("group", Util.getJSONArray(getGroups()));
        addJson(object, "groupList", groupList);
    }

    if (getProfileList() != null)
        addJson(object, "profileList", getProfileList().getJSONObject());
    addJson(object, EXTERNAL_REFERENCE_NAME, isExternalReference());
    addJson(object, getSecurityAttributes());
    return (object);
}

From source file:buri.ddmsence.util.Util.java

License:Open Source License

/**
 * Adds a value to a JSON object, but only if it is not empty and not null.
 * // w w w . j a  v  a 2  s .c  o  m
 * @param object the object to add to
 * @param name the name of the array, if added
 * @param value the value to add
 */
public static void addNonEmptyJsonProperty(JsonObject object, String name, Object value) {
    if (value == null)
        return;
    if (value instanceof AbstractAttributeGroup) {
        AbstractAttributeGroup castValue = (AbstractAttributeGroup) value;
        if (!castValue.isEmpty()) {
            if (Boolean.valueOf(PropertyReader.getProperty("output.json.inlineAttributes"))) {
                JsonObject enclosure = castValue.getJSONObject();
                for (Entry<String, JsonElement> entry : enclosure.entrySet()) {
                    object.add(entry.getKey(), entry.getValue());
                }
            } else {
                object.add(name, castValue.getJSONObject());
            }
        }
    } else if (value instanceof Boolean) {
        Boolean castValue = (Boolean) value;
        object.addProperty(name, castValue);
    } else if (value instanceof Double) {
        Double castValue = (Double) value;
        object.addProperty(name, castValue);
    } else if (value instanceof Integer) {
        Integer castValue = (Integer) value;
        object.addProperty(name, castValue);
    } else if (value instanceof JsonArray) {
        JsonArray castValue = (JsonArray) value;
        if (castValue.size() != 0)
            object.add(name, castValue);
    } else if (value instanceof JsonObject) {
        JsonObject castValue = (JsonObject) value;
        object.add(name, castValue);
    } else if (value instanceof String) {
        String castValue = (String) value;
        if (!Util.isEmpty(castValue))
            object.addProperty(name, castValue);
    } else
        throw new IllegalArgumentException("Unexpected class for JSON property: " + value);
}

From source file:ca.paullalonde.gocd.sns_plugin.executors.NotificationInterestedInExecutor.java

License:Apache License

@Override
public GoPluginApiResponse execute() throws Exception {
    JsonObject jsonObject = new JsonObject();
    JsonArray notifications = new JsonArray();
    notifications.add(REQUEST_STAGE_STATUS.requestName());
    jsonObject.add("notifications", notifications);

    DefaultGoPluginApiResponse defaultGoPluginApiResponse = new DefaultGoPluginApiResponse(200);
    defaultGoPluginApiResponse.setResponseBody(GSON.toJson(jsonObject));
    return defaultGoPluginApiResponse;
}

From source file:ca.ualberta.CMPUT301W15T06.GsonAdapter.java

License:Apache License

@Override
public JsonElement serialize(T src, Type type, JsonSerializationContext context) {
    // TODO Auto-generated method stub
    JsonObject retValue = new JsonObject();
    String className = src.getClass().getCanonicalName();
    retValue.addProperty(CLASSNAME, className);
    JsonElement elem = context.serialize(src);
    retValue.add(INSTANCE, elem);
    return retValue;
}

From source file:ca.ualberta.cs.team1travelexpenseapp.gsonUtils.RuntimeTypeAdapterFactory.java

License:Apache License

public <R> TypeAdapter<R> create(Gson gson, TypeToken<R> type) {
    if (type.getRawType() != baseType) {
        return null;
    }/*w  ww.  ja v  a2  s .  c o m*/

    final Map<String, TypeAdapter<?>> labelToDelegate = new LinkedHashMap<String, TypeAdapter<?>>();
    final Map<Class<?>, TypeAdapter<?>> subtypeToDelegate = new LinkedHashMap<Class<?>, TypeAdapter<?>>();
    for (Map.Entry<String, Class<?>> entry : labelToSubtype.entrySet()) {
        TypeAdapter<?> delegate = gson.getDelegateAdapter(this, TypeToken.get(entry.getValue()));
        labelToDelegate.put(entry.getKey(), delegate);
        subtypeToDelegate.put(entry.getValue(), delegate);
    }

    return new TypeAdapter<R>() {
        @Override
        public R read(JsonReader in) throws IOException {
            JsonElement jsonElement = Streams.parse(in);
            JsonElement labelJsonElement = jsonElement.getAsJsonObject().remove(typeFieldName);
            if (labelJsonElement == null) {
                throw new JsonParseException("cannot deserialize " + baseType
                        + " because it does not define a field named " + typeFieldName);
            }
            String label = labelJsonElement.getAsString();
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) labelToDelegate.get(label);
            if (delegate == null) {
                throw new JsonParseException("cannot deserialize " + baseType + " subtype named " + label
                        + "; did you forget to register a subtype?");
            }
            return delegate.fromJsonTree(jsonElement);
        }

        @Override
        public void write(JsonWriter out, R value) throws IOException {
            Class<?> srcType = value.getClass();
            String label = subtypeToLabel.get(srcType);
            @SuppressWarnings("unchecked") // registration requires that subtype extends T
            TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
            if (delegate == null) {
                throw new JsonParseException(
                        "cannot serialize " + srcType.getName() + "; did you forget to register a subtype?");
            }
            JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
            if (jsonObject.has(typeFieldName)) {
                throw new JsonParseException("cannot serialize " + srcType.getName()
                        + " because it already defines a field named " + typeFieldName);
            }
            JsonObject clone = new JsonObject();
            clone.add(typeFieldName, new JsonPrimitive(label));
            for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
                clone.add(e.getKey(), e.getValue());
            }
            Streams.write(clone, out);
        }
    };
}

From source file:carsharing.starter.automotive.iot.ibm.com.mobilestarterapp.AnalyzeMyDriving.java

License:Open Source License

public void sendLocation(final Location location) {
    if (connectDeviceClient()) {
        final GregorianCalendar cal = new GregorianCalendar();
        final TimeZone gmt = TimeZone.getTimeZone("GMT");
        cal.setTimeZone(gmt);//from   ww w .  j  a v a  2s .co  m
        final SimpleDateFormat formattedCal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        formattedCal.setCalendar(cal);
        final String timestamp = formattedCal.format(cal.getTime());

        final double speed = Math.max(0.0, location.getSpeed() * 60 * 60 / 1000);
        final double longitude = location.getLongitude();
        final double latitude = location.getLatitude();
        final String mobileAppDeviceId = FirstPage.mobileAppDeviceId;
        final String status = tripID != null ? "Unlocked" : "Locked";

        if (tripID == null) {
            // this trip should be completed, so lock device now
            userUnlocked = false;
        }

        final JsonObject event = new JsonObject();
        final JsonObject data = new JsonObject();
        event.add("d", data);
        data.addProperty("trip_id", tripID);
        data.addProperty("speed", speed);
        data.addProperty("lng", longitude);
        data.addProperty("lat", latitude);
        data.addProperty("ts", timestamp);
        data.addProperty("id", mobileAppDeviceId);
        data.addProperty("status", status);

        final ActionBar supportActionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if (deviceClient.publishEvent("sensorData", event, 0)) {
            Log.d("MQTT", "publish event " + event.toString());
            supportActionBar.setTitle(speedMessage + " - Data sent (" + (++transmissionCount) + ")");
        } else {
            Log.d("MQTT", "ERROR in publishing event " + event.toString());
            supportActionBar.setTitle("Data Transmission Error.");
        }
    }
}