Example usage for com.google.gson JsonElement toString

List of usage examples for com.google.gson JsonElement toString

Introduction

In this page you can find the example usage for com.google.gson JsonElement toString.

Prototype

@Override
public String toString() 

Source Link

Document

Returns a String representation of this element.

Usage

From source file:controllers.VotacionRecController.java

License:Open Source License

@RequestMapping(value = "/seeId")
@ResponseBody/*from w w w .  j a v  a  2  s.com*/
public String recuentaVotacion(@RequestParam int vot) {
    String result;
    JsonElement json;
    VotacionRec votacionRec = votacionRecService.findOne(vot);
    Gson gson = new Gson();
    json = gson.toJsonTree(votacionRec);
    result = json.toString();
    return result;
}

From source file:csh.vctt.datautils.DataManager.java

License:Apache License

/**
 * Returns a member of a JSON object as a String.
 * @param obj JsonObject to be parsed into String.
 * @param memberName The member's name in the JSON.
 * @return Member's String value./* w  w w.  j ava  2 s. c o  m*/
 */
private static String getMemberAsStr(JsonObject obj, String memberName) {
    JsonElement elem = obj.get(memberName);
    String elemStr = elem.toString();
    elemStr = elemStr.replace("\"", "");

    return elemStr;
}

From source file:de.arkraft.jenkins.JenkinsHelper.java

License:Apache License

public static GsonBuilder getGsonBuilder() {
    GsonBuilder builder = new GsonBuilder();

    builder.registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() {
        @Override// w w w .  j  a  v  a  2 s .  c  om
        public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            // using the correct parser right away should save init time compared to new DateTime(<string>)
            return ISO_8601_WITH_MILLIS.parseDateTime(json.getAsString());
        }
    });

    builder.registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() {
        @Override
        public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) {
            return new JsonPrimitive(src.toString());
        }
    });

    builder.registerTypeAdapter(Duration.class, new JsonDeserializer() {
        @Override
        public Object deserialize(JsonElement json, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return Duration.parse("PT" + json.getAsString() + "S");
        }
    });

    builder.registerTypeAdapter(Action.class, new JsonDeserializer<Action>() {
        @Override
        public Action deserialize(JsonElement jsonElement, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

            JsonObject object = ((JsonObject) jsonElement);
            if (object.has("causes")) {
                JsonElement element = object.get("causes");
                if (element.isJsonArray()) {
                    return jsonDeserializationContext.deserialize(element, Causes.class);
                }
            }
            if (object.has("failCount")) {
                return jsonDeserializationContext.deserialize(object, CountAction.class);
            }
            return null;
        }
    });

    builder.registerTypeAdapter(ChangeSet.class, new JsonDeserializer<ChangeSet>() {
        @Override
        public ChangeSet deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            ChangeSet changeSet = new ChangeSet();
            JsonObject object = (JsonObject) jsonElement;
            if (object.has("items") && object.get("items").isJsonArray()) {
                for (JsonElement element : object.get("items").getAsJsonArray()) {
                    ChangeSet.Change change = context.deserialize(element, ChangeSet.Change.class);
                    changeSet.add(change);
                }
            }
            if (object.has("kind")) {
                changeSet.setKind(object.get("kind").getAsString());
            }
            return changeSet;
        }
    });

    builder.registerTypeAdapter(Duration.class, new JsonSerializer<Duration>() {
        @Override
        public JsonElement serialize(Duration duration, Type type,
                JsonSerializationContext jsonSerializationContext) {
            return new JsonPrimitive(duration.toString().replace("PT", "").replace("S", ""));
        }
    });

    builder.registerTypeAdapter(EditType.class, new JsonDeserializer<EditType>() {
        @Override
        public EditType deserialize(JsonElement jsonElement, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return EditType.byName(jsonElement.getAsString());
        }
    });

    builder.registerTypeAdapter(HealthIcon.class, new JsonDeserializer<HealthIcon>() {
        @Override
        public HealthIcon deserialize(JsonElement jsonElement, Type type,
                JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            return HealthIcon.fromName(jsonElement.toString());
        }
    });

    builder.registerTypeAdapter(Queue.class, new JsonDeserializer<Queue>() {
        @Override
        public Queue deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            Queue queue = new Queue();
            JsonObject jsonObject = (JsonObject) jsonElement;
            if (jsonObject.has("items") && jsonObject.get("items").isJsonArray()) {
                for (JsonElement element : jsonObject.get("items").getAsJsonArray()) {
                    Queue.Item build = context.deserialize(element, Queue.Item.class);
                    queue.add(build);
                }
            }
            return queue;
        }
    });

    builder.registerTypeAdapter(JobCollection.class, new JsonDeserializer<JobCollection>() {
        @Override
        public JobCollection deserialize(JsonElement json, Type type, JsonDeserializationContext context)
                throws JsonParseException {
            JobCollection jobs = new JobCollection();
            JsonObject object = (JsonObject) json;
            if (object.has("jobs") && object.get("jobs").isJsonArray()) {
                for (JsonElement element : object.get("jobs").getAsJsonArray()) {
                    Job job = context.deserialize(element, Job.class);
                    jobs.add(job);
                }
            }
            return jobs;
        }
    });

    builder.registerTypeAdapter(BallColor.class, new JsonDeserializer<BallColor>() {
        @Override
        public BallColor deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext json)
                throws JsonParseException {
            return BallColor.valueOf(jsonElement.getAsString().toUpperCase());
        }
    });

    return builder;
}

From source file:de.azapps.mirakel.model.list.SpecialListsWhereDeserializer.java

License:Open Source License

@NonNull
private static Optional<SpecialListsBaseProperty> parseSpecialListsCondition(
        final @NonNull JsonElement element) {
    final JsonObject obj = element.getAsJsonObject();
    final Class<? extends SpecialListsBaseProperty> className;
    final String key;
    if (obj.has(Task.LIST_ID)) {
        key = Task.LIST_ID;/*  w  w w . j  a  v  a2 s. c  o m*/
        className = SpecialListsListProperty.class;
    } else if (obj.has(ModelBase.NAME)) {
        key = Task.NAME;
        className = SpecialListsNameProperty.class;
    } else if (obj.has(Task.PRIORITY)) {
        key = Task.PRIORITY;
        className = SpecialListsPriorityProperty.class;
    } else if (obj.has(Task.DONE)) {
        key = Task.DONE;
        className = SpecialListsDoneProperty.class;
    } else if (obj.has(Task.DUE)) {
        key = Task.DUE;
        className = SpecialListsDueProperty.class;
    } else if (obj.has(Task.CONTENT)) {
        key = Task.CONTENT;
        className = SpecialListsContentProperty.class;
    } else if (obj.has(Task.REMINDER)) {
        key = Task.REMINDER;
        className = SpecialListsReminderProperty.class;
    } else if (obj.has(Task.PROGRESS)) {
        key = Task.PROGRESS;
        className = SpecialListsProgressProperty.class;
    } else if (obj.has(Task.SUBTASK_TABLE)) {
        key = Task.SUBTASK_TABLE;
        className = SpecialListsSubtaskProperty.class;
    } else if (obj.has(FileMirakel.TABLE)) {
        key = FileMirakel.TABLE;
        className = SpecialListsFileProperty.class;
    } else if (obj.has(Tag.TABLE)) {
        key = Tag.TABLE;
        className = SpecialListsTagProperty.class;
    } else if (obj.has(ListMirakel.TABLE + '.' + ListMirakel.NAME)) {
        key = ListMirakel.TABLE + '.' + ListMirakel.NAME;
        className = SpecialListsListNameProperty.class;
    } else if (obj.has(Task.DUE + "_exists")) {
        key = Task.DUE + "_exists";
        className = SpecialListsDueExistsProperty.class;
    } else if ("{}".equals(element.toString())) {
        return absent();
    } else {
        Log.wtf(TAG, "unknown query object: " + obj.toString());
        Log.v(TAG, "implement this?");
        throw new IllegalArgumentException("unknown query object: " + obj.toString());
    }
    final SpecialListsBaseProperty prop = gson.fromJson(obj.get(key), className);
    return of(prop);
}

From source file:de.dfki.mmf.attributeselection.AttributeSelectionAlgorithm.java

License:Open Source License

/**
 * @return list with JsonObjects each containing those attributes of the queried object which discriminates it from the compared database object
 *//*  w w  w .  ja va 2s. com*/
public List<JsonObject> computeSingleDiscriminatingIdentifiers() {
    //data structure to save discriminating identifiers resulting from the comparisons between queried object and each database object
    ArrayList<JsonObject> identifiers = new ArrayList<>();
    for (JsonObject databaseObject : databaseObjects) {
        //create list for each comparison of queried object properties and the properties of a database object
        // to save property values which uniquely identify queried object
        JsonObject singleDiscriminatingIdentifiers = new JsonObject();
        //go over each property of the queried object
        Set<Map.Entry<String, JsonElement>> entrySet = queriedObject.entrySet();
        for (Map.Entry<String, JsonElement> entry : entrySet) {
            String queryKey = entry.getKey();
            //check saliencyAnnotation is exists
            if (saliencyAnnotations != null) {
                //look up the saliency annotation of the object
                if (saliencyAnnotations.has(queryKey)) {
                    double saliencyNbr = saliencyAnnotations.get(queryKey).getAsDouble();
                    //if saliency is lower than threshold -> property will be pruned, continue with next property
                    if (saliencyNbr < saliencyThreshold) {
                        continue;
                    }
                } else {
                    continue;
                }
            }
            //the values the queried object has for certain property
            JsonElement queriedPropertyValues = queriedObject.get(queryKey);
            //check if database object has this property
            if (databaseObject.has(queryKey)) {
                //get the values the database object has for this property
                JsonElement dataPropertyValues = databaseObject.get(queryKey);
                //check if objects have the same values for this property -> if not add values of queried object to list
                if ((queriedPropertyValues.isJsonArray() && !dataPropertyValues.isJsonArray())
                        || (!queriedPropertyValues.isJsonArray() && dataPropertyValues.isJsonArray())) {
                    singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues);
                } else if (!queriedPropertyValues.isJsonArray() && !dataPropertyValues.isJsonArray()) {
                    if (!Objects.equals(queriedPropertyValues.toString(), dataPropertyValues.toString())) {
                        singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues);
                    }
                } else if (queriedPropertyValues.isJsonArray() && dataPropertyValues.isJsonArray()) {
                    JsonArray queryArray = queriedPropertyValues.getAsJsonArray();
                    JsonArray dataArray = dataPropertyValues.getAsJsonArray();
                    boolean added = false;
                    for (JsonElement queryElement : queryArray) {
                        if (!dataArray.contains(queryElement)) {
                            singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues);
                            added = true;
                            break;
                        }
                    }
                    if (!added) {
                        for (JsonElement dataElement : dataArray) {
                            if (!queryArray.contains(dataElement)) {
                                singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues);
                                break;
                            }
                        }
                    }
                }
                //compared database object does not have particular property -> can be seen as differentiating
            } else {
                singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues);
            }
        }
        //add single discriminating identifiers to list with all found identifiers
        identifiers.add(singleDiscriminatingIdentifiers);
    }
    return identifiers;
}

From source file:de.hshannover.f4.trust.irongpm.rest.VisitmetaResource.java

License:Apache License

/**
 * Requests the REST interface for the given path, e.g. "current" or "changes"
 * //from   w  w w  .jav  a  2  s .co  m
 * @param path
 *            The path for the HTTP request
 * @return The JSON response string
 */
public String get(String path) {
    String json = null;
    boolean connected = true;
    do {
        try {
            URLConnection conn = new URL(mBaseUrl + path + "?rawData=" + mRawXml).openConnection();
            conn.setConnectTimeout(2000);
            conn.connect();
            JsonReader reader = new JsonReader(new InputStreamReader(conn.getInputStream()));
            JsonParser parser = new JsonParser();
            JsonElement rootElement = parser.parse(reader);
            json = rootElement.toString();
            if (!connected) {
                LOGGER.info("VisitmetaResource connection (re-)established");
            }
            connected = true;
        } catch (Exception e) {
            try {
                LOGGER.warn("VisitmetaResource connection failed on " + mBaseUrl
                        + ". Trying again in 5 seconds. Reason: [" + e + "]");
                Thread.sleep(5000);
            } catch (InterruptedException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            connected = false;
        }
    } while (!connected);
    return json;
}

From source file:de.innovationgate.wgpublisher.expressions.tmlscript.RhinoExpressionEngineImpl.java

License:Open Source License

@Override
public void injectProperty(Object controllerObj, String prop, JsonElement state) {
    Scriptable controller = (Scriptable) controllerObj;
    controller.put(prop, controller, convertJsonToScriptable(state.toString()));
}

From source file:dpfmanager.shell.modules.report.util.ReportRow.java

License:Open Source License

/**
 * Create row from json report row.//from ww w  . ja v  a  2s . c  om
 *
 * @param reportDay the report day
 * @param file      the file
 * @return the report row
 */
public static ReportRow createRowFromJson(String reportDay, File file, ResourceBundle bundle) {
    try {
        String sdate = reportDay.substring(6, 8) + "/" + reportDay.substring(4, 6) + "/"
                + reportDay.substring(0, 4);
        File parent = new File(file.getParent());
        int n = countFiles(parent, ".json") - 1 - countFiles(parent, "_fixed.json");
        int passed = 0, errors = 0, warnings = 0, score = 0;
        String json = readFullFile(file.getPath(), Charset.defaultCharset());
        JsonObject jObjRoot = new JsonParser().parse(json).getAsJsonObject();
        String stime = getStime(file.getPath());
        String input = parseInputFiles(file.getParentFile(), file.getAbsolutePath(), ".json");
        JsonObject jObj = jObjRoot.getAsJsonObject("globalreport");

        // Passed
        if (jObj.has("stats")) {
            try {
                JsonObject jStats = jObj.get("stats").getAsJsonObject();
                passed = Integer.parseInt(jStats.get("valid_files").getAsString());
            } catch (Exception e) {
                passed = -1;
            }
        }

        // Errors
        if (jObj.has("stats")) {
            try {
                JsonObject jStats = jObj.get("stats").getAsJsonObject();
                errors = Integer.parseInt(jStats.get("invalid_files").getAsString());
            } catch (Exception e) {
                errors = -1;
            }
        }

        // Warnings
        if (jObj.has("individualreports")) {
            try {
                JsonArray jArray = ((JsonObject) jObj.get("individualreports")).get("report").getAsJsonArray()
                        .getAsJsonArray();
                for (JsonElement element : jArray) {
                    if (element.toString().contains("\"warning\"")) {
                        warnings++;
                    }
                }
            } catch (Exception e) {
                warnings = -1;
            }
        }

        // Score
        if (n > 0) {
            score = passed * 100 / n;
        }

        ReportRow row = new ReportRow(sdate, stime, input, "" + n,
                bundle.getString("errors").replace("%1", "" + errors),
                bundle.getString("warnings").replace("%1", "" + warnings),
                bundle.getString("passed").replace("%1", "" + passed), score + "%", file.getAbsolutePath());
        return row;
    } catch (Exception e) {
        return null;
    }
}

From source file:DS.Model.java

private String parseResponse(String json) {
    JsonParser parser = new JsonParser();
    JsonElement jsonTree = parser.parse(json); //Parse json from yelp
    JsonObject jsonReply = new JsonObject();
    JsonArray jsonReplyArray = new JsonArray(); //The json that will be sent to Android

    //Check to see if the json element is a json object
    if (jsonTree.isJsonObject()) {
        JsonObject jsonObject = jsonTree.getAsJsonObject();
        JsonArray jarray = jsonObject.getAsJsonArray("businesses");

        //Loop through the businesses that were sent in the json array
        Iterator i = jarray.iterator();
        while (i.hasNext()) {
            //get the name, rating, and address from the business
            //Add the information to the replyBusiness json which will be sent to Android
            JsonObject replyBusiness = new JsonObject();
            JsonObject business = (JsonObject) i.next();

            String name = business.get("name").getAsString();
            replyBusiness.addProperty("name", name);

            String rating = business.get("rating").getAsString();
            replyBusiness.addProperty("rating", rating);

            JsonElement location = business.get("location");
            JsonObject locObject = location.getAsJsonObject();
            JsonArray addressArray = locObject.getAsJsonArray("display_address");
            Iterator i2 = addressArray.iterator();
            String displayAddress = "";

            //The address is split across multiple lines, so retrieve all lines and combine into one line
            while (i2.hasNext()) {
                JsonElement line = (JsonElement) i2.next();
                displayAddress += line.toString();
            }//www.ja  v a 2s  . c o m
            displayAddress = displayAddress.replaceAll("\\\"+", " ").trim();
            replyBusiness.addProperty("address", displayAddress);
            jsonReplyArray.add(replyBusiness);

            //Try and log the restaurant to the mongodb database
            try {
                MongoConnect();
                logRestaurant(name, Double.parseDouble(rating), displayAddress);
            } finally {
                CloseMongo();
            }
        }
        jsonReply.add("businesses", jsonReplyArray);
    }

    //Returns the json string containing 3 restaurants to android
    return jsonReply.toString();
}

From source file:edu.harvard.iq.dataverse.datasetutility.FileUploadTestPage.java

private void checkRetrievalTest() {
    msgt("checkRetrievalTest");
    if (dataset == null) {
        msg("Dataset is null!!!");
    }/*from  www.j  av  a2  s .  c o  m*/
    boolean prettyPrint = true;

    List<HashMap> hashList = datasetVersionService.getBasicDatasetVersionInfo(dataset);
    if (hashList == null) {
        msg("hashList is null!!!");
        return;

    }

    msgt("hashed! : " + hashList.size());

    msg(hashList.toString());

    GsonBuilder builder;
    if (prettyPrint) { // Add pretty printing
        builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setPrettyPrinting();
    } else {
        builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation();
    }

    Gson gson = builder.create();

    // ----------------------------------
    // serialize this object + add the id
    // ----------------------------------
    JsonElement jsonObj = gson.toJsonTree(hashList);
    msgt("Really?");
    msg(jsonObj.toString());

}