Example usage for com.google.gson JsonObject has

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

Introduction

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

Prototype

public boolean has(String memberName) 

Source Link

Document

Convenience method to check if a member with the specified name is present in this object.

Usage

From source file:app.abhijit.iter.data.source.StudentDataSource.java

License:Open Source License

private void processStudentSubjects(String response) {
    mFetchStudentSubjectsAsyncTask = null;

    JsonObject student = mJsonParser.parse(mLocalStore.getString(mSelectedRegistrationNumber, null))
            .getAsJsonObject();/*from w  w  w  .java2 s.  c o  m*/
    JsonObject subjects = new JsonObject();

    try {
        JsonArray studentSubjects = mJsonParser.parse(response).getAsJsonArray();
        for (int i = 0; i < studentSubjects.size(); i++) {
            if (!studentSubjects.get(i).getAsJsonObject().has("subjectcode")
                    || !studentSubjects.get(i).getAsJsonObject().has("subject")
                    || !studentSubjects.get(i).getAsJsonObject().has("totalpresentclass")
                    || !studentSubjects.get(i).getAsJsonObject().has("totalclasses")) {
                continue;
            }
            String code = studentSubjects.get(i).getAsJsonObject().get("subjectcode").getAsString();
            String name = studentSubjects.get(i).getAsJsonObject().get("subject").getAsString();
            int presentClasses = studentSubjects.get(i).getAsJsonObject().get("totalpresentclass").getAsInt();
            int totalClasses = studentSubjects.get(i).getAsJsonObject().get("totalclasses").getAsInt();
            if (totalClasses <= 0 || presentClasses < 0 || presentClasses > totalClasses)
                continue;
            long lastUpdated = new Date().getTime();
            int oldPresentClasses = presentClasses;
            int oldTotalClasses = totalClasses;
            if (student.has(STUDENT_SUBJECTS_KEY)
                    && student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().has(code)) {
                oldPresentClasses = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code)
                        .getAsJsonObject().get(STUDENT_SUBJECT_PRESENT_CLASSES_KEY).getAsInt();
                oldTotalClasses = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code)
                        .getAsJsonObject().get(STUDENT_SUBJECT_TOTAL_CLASSES_KEY).getAsInt();
                if (presentClasses == oldPresentClasses && totalClasses == oldTotalClasses) {
                    lastUpdated = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(code)
                            .getAsJsonObject().get(STUDENT_SUBJECT_LAST_UPDATED_KEY).getAsLong();
                }
            }
            JsonObject subject = new JsonObject();
            subject.addProperty(STUDENT_SUBJECT_CODE_KEY, code);
            subject.addProperty(STUDENT_SUBJECT_NAME_KEY, name);
            subject.addProperty(STUDENT_SUBJECT_PRESENT_CLASSES_KEY, presentClasses);
            subject.addProperty(STUDENT_SUBJECT_TOTAL_CLASSES_KEY, totalClasses);
            subject.addProperty(STUDENT_SUBJECT_OLD_PRESENT_CLASSES_KEY, oldPresentClasses);
            subject.addProperty(STUDENT_SUBJECT_OLD_TOTAL_CLASSES_KEY, oldTotalClasses);
            subject.addProperty(STUDENT_SUBJECT_LAST_UPDATED_KEY, lastUpdated);
            subjects.add(code, subject);
        }
    } catch (Exception e) {
        if (student.has(STUDENT_SUBJECTS_KEY)) {
            subjects = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject();
        } else {
            subjects = new JsonObject();
        }
    }

    student.add(STUDENT_SUBJECTS_KEY, subjects);
    student.addProperty(STUDENT_TIMESTAMP_KEY, new Date().getTime());
    mLocalStore.edit().putString(mSelectedRegistrationNumber, student.toString()).apply();

    fetch();
}

From source file:app.abhijit.iter.data.source.StudentDataSource.java

License:Open Source License

private Student generateStudent(JsonObject student) {
    String registrationNumber = student.get(STUDENT_REGISTRATION_NUMBER_KEY).getAsString();
    String name = null;/*  ww w  .  j  a v  a 2  s.co  m*/
    if (student.has(STUDENT_NAME_KEY)) {
        name = WordUtils.capitalizeFully(student.get(STUDENT_NAME_KEY).getAsString());
    }
    boolean selected = StringUtils.equals(registrationNumber, mSelectedRegistrationNumber);

    ArrayList<Subject> subjects = new ArrayList<>();

    if (StringUtils.equals(mSelectedRegistrationNumber, registrationNumber)
            && mFetchStudentSubjectsAsyncTask == null && student.has(STUDENT_SUBJECTS_KEY)) {
        for (Map.Entry<String, ?> entry : student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().entrySet()) {
            JsonObject subject = student.get(STUDENT_SUBJECTS_KEY).getAsJsonObject().get(entry.getKey())
                    .getAsJsonObject();
            subjects.add(generateStudentSubject(subject));
            removeOldSubjectData(registrationNumber, student, subject);
        }
    } else {
        subjects = null;
    }

    return new Student(name, registrationNumber, selected,
            subjects == null ? null : ImmutableList.copyOf(subjects));
}

From source file:aproject.App.java

License:Apache License

public static JsonObject main(JsonObject args) {
    String name = "stranger";
    if (args.has("name"))
        name = args.getAsJsonPrimitive("name").getAsString();
    JsonObject response = new JsonObject();
    response.addProperty("greeting", "Hello " + name + "!");
    return response;
}

From source file:at.orz.arangodb.entity.EntityDeserializers.java

License:Apache License

private static <T extends BaseEntity> T deserializeBaseParameter(JsonObject obj, T entity) {

    if (obj.has("error")) {
        entity.error = obj.getAsJsonPrimitive("error").getAsBoolean();
    }/*  w  w w  . j  av  a 2  s.  c  om*/
    if (obj.has("code")) {
        entity.code = obj.getAsJsonPrimitive("code").getAsInt();
    }
    if (obj.has("errorNum")) {
        entity.errorNumber = obj.getAsJsonPrimitive("errorNum").getAsInt();
    }
    if (obj.has("errorMessage")) {
        entity.errorMessage = obj.getAsJsonPrimitive("errorMessage").getAsString();
    }
    if (obj.has("etag")) {
        entity.etag = obj.getAsJsonPrimitive("etag").getAsLong();
    }

    return entity;
}

From source file:at.orz.arangodb.entity.EntityDeserializers.java

License:Apache License

private static <T extends DocumentHolder> T deserializeDocumentParameter(JsonObject obj, T entity) {

    if (obj.has("_rev")) {
        entity.setDocumentRevision(obj.getAsJsonPrimitive("_rev").getAsLong());
    }/*from  www  .  j  a  v a 2 s  .c  om*/
    if (obj.has("_id")) {
        entity.setDocumentHandle(obj.getAsJsonPrimitive("_id").getAsString());
    }
    if (obj.has("_key")) {
        entity.setDocumentKey(obj.getAsJsonPrimitive("_key").getAsString());
    }

    return entity;
}

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

private Map<Long, User> json2Users(JsonObject json) {
    HashMap<Long, User> users = new HashMap<Long, User>();
    JsonObject block = json.get(SECTION_U).getAsJsonObject();

    Set<Entry<String, JsonElement>> entries = block.entrySet();
    for (Entry<String, JsonElement> u : entries) {
        JsonObject jsUser = u.getValue().getAsJsonObject();
        System.out.println(jsUser.toString());
        String uname;//  w w w.  j a  v  a2 s.  c  o  m
        if (jsUser.has(NAME))
            uname = jsUser.get(NAME).getAsString();
        else
            uname = "";
        String uDescr;
        if (jsUser.has(DESCRIPTION))
            uDescr = jsUser.get(DESCRIPTION).getAsString();
        else
            uDescr = "";
        String externalUID;
        if (jsUser.has(E_UID))
            externalUID = jsUser.get(E_UID).getAsString();
        else
            externalUID = "";
        User user = new User(externalUID, uname, uDescr);
        users.put(Long.parseLong(u.getKey()), user);
    }
    return users;
}

From source file:at.tugraz.kmi.medokyservice.fca.util.ImportExport.java

License:Open Source License

@SuppressWarnings("unchecked")
private <E extends FCAAbstract> Map<Long, E> json2Absctract(JsonObject json,
        Map<Long, LearningObject> learningObjects, Class<E> type) {
    HashMap<Long, E> objects = new HashMap<Long, E>();
    JsonObject block = null;//  w w w  .  j a va  2s .  co  m
    if (type == FCAObject.class)
        block = json.get(SECTION_O).getAsJsonObject();
    else if (type == FCAAttribute.class)
        block = json.get(SECTION_A).getAsJsonObject();
    Set<Entry<String, JsonElement>> entries = block.entrySet();
    for (Entry<String, JsonElement> o : entries) {
        JsonObject jsO = o.getValue().getAsJsonObject();
        E object;
        String creationId;
        if (!jsO.has(CID)) {
            double num = rand.nextDouble() * 10000;
            int val = (int) num;
            creationId = Integer.toString(val, 16);
        } else
            creationId = jsO.get(CID).getAsString();
        if (type == FCAObject.class)
            object = (E) new FCAObject(jsO.get(NAME).getAsString(), jsO.get(DESCRIPTION).getAsString(),
                    creationId);
        else
            object = (E) new FCAAttribute(jsO.get(NAME).getAsString(), jsO.get(DESCRIPTION).getAsString(),
                    creationId);
        Set<LearningObject> lObjs = new HashSet<LearningObject>();
        Set<LearningObject> lObjsByLearner = new HashSet<LearningObject>();
        Iterator<JsonElement> lOs = jsO.getAsJsonArray(SECTION_LO).iterator();
        while (lOs.hasNext()) {
            LearningObject lo = learningObjects.get((lOs.next().getAsLong()));
            if (lo != null)
                lObjs.add(lo);
        }
        try {
            Iterator<JsonElement> lOsByLearner = jsO.getAsJsonArray(SECTION_LO_L).iterator();
            while (lOsByLearner.hasNext()) {
                LearningObject lo = learningObjects.get((lOsByLearner.next().getAsLong()));
                if (lo != null)
                    lObjsByLearner.add(lo);
            }
        } catch (Exception notAnError) {

        }
        clean(lObjsByLearner);
        object.setLearningObjectsByLearners(lObjsByLearner);
        clean(lObjs);
        object.setLearningObjects(lObjs);
        objects.put(Long.parseLong(o.getKey()), object);
    }
    return objects;
}

From source file:au.edu.ausstage.tweetgatherer.MessageProcessor.java

License:Open Source License

/**
 * A private method to sanitise the message
 *
 * @param jsonTweetObject the original message object
 * @param idHash          the hash of the message id
 *
 * @return                the sanitised message object
 *//*from w w w. ja  v a  2  s.c  o  m*/
private JsonObject sanitiseMessage(JsonObject jsonTweetObject, String idHash) {

    // remove the id and replace it with the hash
    jsonTweetObject.remove("id");
    jsonTweetObject.addProperty("id", idHash);

    // replace the "in_reply_to_user_id" field with a hash if present
    if (jsonTweetObject.has("in_reply_to_user_id") == true) {

        // get a hash of the value
        JsonElement elem = jsonTweetObject.get("in_reply_to_user_id");
        if (elem.isJsonNull() == false) {
            String hash = HashUtils.hashValue(elem.getAsString());

            // update the value
            jsonTweetObject.remove("in_reply_to_user_id");
            jsonTweetObject.addProperty("in_reply_to_user_id", hash);
        }
    }

    // replace the "in_reply_to_status_id" field with a hash if present
    if (jsonTweetObject.has("in_reply_to_status_id") == true) {

        // get a hash of the value
        JsonElement elem = jsonTweetObject.get("in_reply_to_status_id");
        if (elem.isJsonNull() == false) {
            String hash = HashUtils.hashValue(elem.getAsString());

            // update the value
            jsonTweetObject.remove("in_reply_to_status_id");
            jsonTweetObject.addProperty("in_reply_to_status_id", hash);
        }
    }

    // replace the "retweeted_status" field with a hash if present
    if (jsonTweetObject.has("retweeted_status") == true) {

        // get a hash of the value
        JsonElement elem = jsonTweetObject.get("retweeted_status");
        if (elem.isJsonNull() == false) {
            String hash = HashUtils.hashValue(elem.getAsString());

            // update the value
            jsonTweetObject.remove("retweeted_status");
            jsonTweetObject.addProperty("retweeted_status", hash);
        }
    }

    // return the sanitised object
    return jsonTweetObject;

}

From source file:au.edu.ausstage.tweetgatherer.MessageProcessor.java

License:Open Source License

/**
 * A private method to sanitise the message
 *
 * @param jsonTweetObject the original user object
 * @param idHash          the hash of the user id
 *
 * @return                the sanitised user object
 *//*from  ww  w .j  a v  a2s  . c om*/
private JsonObject sanitiseUser(JsonObject jsonTweetObject, String idHash) {

    // remove the id and replace it with the hash
    jsonTweetObject.remove("id");
    jsonTweetObject.addProperty("id", idHash);

    // loop through the list of sanitised fields
    for (int i = 0; i < SANITISED_FIELDS.length; i++) {
        if (jsonTweetObject.has(SANITISED_FIELDS[i]) == true) {
            jsonTweetObject.remove(SANITISED_FIELDS[i]);
            jsonTweetObject.addProperty(SANITISED_FIELDS[i], "");
        }
    }

    // return the sanitised object
    return jsonTweetObject;
}

From source file:au.edu.unsw.soacourse.client.ApplicationLogic.java

static public void getAppsByJobID(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("utf8");
    response.setContentType("application/json");
    PrintWriter out = response.getWriter();
    try {//from  ww  w .j  a v  a2  s  . c  o  m
        StringBuffer sb = new StringBuffer();
        BufferedReader reader = request.getReader();
        String temp = "";
        while ((temp = reader.readLine()) != null) {
            sb.append(temp);
        }
        // System.out.println(sb.toString());
        // convert to object
        Gson gson = new Gson();
        JsonElement je = gson.fromJson(sb.toString(), JsonElement.class);
        JsonObject jo = je.getAsJsonObject();

        String jobID = "";
        if (jo.has("jobID"))
            jobID = jo.get("jobID").getAsString();

        String REST_URI = "http://localhost:8080/RESTfulFoundITService/apps";
        REST_URI += "/jobID/" + jobID;

        WebClient client = WebClient.create(REST_URI);
        String s = client.get(String.class);
        // System.out.println(s);

        // write to json

        out.write(s);
        out.close();
    } catch (Exception e) {
        out.write("failed");
        e.printStackTrace();
        out.close();
    }

}