Example usage for com.google.gson JsonParser parse

List of usage examples for com.google.gson JsonParser parse

Introduction

In this page you can find the example usage for com.google.gson JsonParser parse.

Prototype

@Deprecated
public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException 

Source Link

Usage

From source file:algorithmi.models.UserCourse.java

License:Apache License

public UserCourse(String data) {

    //Transforma a string recebida pelo pedido http para json
    JsonParser jsonParser = new JsonParser();
    JsonObject UserCourse = (JsonObject) jsonParser.parse(data);
    //Exibe os dados, em formato json
    System.out.println(UserCourse.entrySet());
    /**/*from   w w  w .java2  s. c o  m*/
     *
     * Revalidar TUDO, formatos, campos vazios, TUDO!!
     *
     */
    validateData();
    //Associa os dados ao objecto UserCourse
    this.user = UserCourse.get("_id").getAsInt();
    ; //ir buscar o max id da bd + 1 
    this.course = UserCourse.get("codCourse").getAsInt();

}

From source file:ambari.interaction.NodeController.java

public static ArrayList<ComponentInformation> getListOfNodes() throws Exception {
    String url = "http://127.0.0.1:8080/api/v1/clusters/mycluster/services/HDFS/components/DATANODE?fields=host_components/HostRoles/desired_admin_state,host_components/HostRoles/state";
    String responseJson = HttpURLConnectionExample.sendGet(url);
    System.out.print(responseJson);
    JsonParser jsonParser = new JsonParser();
    JsonElement jsonTree = jsonParser.parse(responseJson);
    ArrayList<ComponentInformation> listOfCompoents = new ArrayList<ComponentInformation>();

    if (jsonTree.isJsonObject()) {
        JsonObject jsonObject = jsonTree.getAsJsonObject();
        JsonElement hostComponents = jsonObject.get("host_components");

        if (hostComponents.isJsonArray()) {
            JsonArray hostComponentsJsonArray = hostComponents.getAsJsonArray();
            System.out.println("\nStart");
            System.out.println(hostComponentsJsonArray);

            for (int i = 0; i < hostComponentsJsonArray.size(); i++) {
                JsonElement hostComponentsElem = hostComponentsJsonArray.get(i);

                if (hostComponentsElem.isJsonObject()) {
                    JsonObject jsonObjectElem = hostComponentsElem.getAsJsonObject();
                    JsonElement hostRolesElem = jsonObjectElem.get("HostRoles");

                    if (hostRolesElem.isJsonObject()) {
                        JsonObject hostRolesObjs = hostRolesElem.getAsJsonObject();
                        JsonElement componentNameElem = hostRolesObjs.get("component_name");
                        JsonElement hostNameElem = hostRolesObjs.get("host_name");
                        JsonElement stateElem = hostRolesObjs.get("state");

                        listOfCompoents.add(new ComponentInformation(componentNameElem.toString(),
                                hostNameElem.toString(), stateElem.toString()));
                    }//from w w  w  .j  a v a2  s.c  om
                }
            }
        }
    }

    return listOfCompoents;
}

From source file:angularBeans.util.AngularBeansUtil.java

License:Open Source License

public static JsonObject parse(String message) {

    JsonParser parser = new JsonParser();
    JsonElement element = parser.parse(message);

    JsonObject jObj = element.getAsJsonObject();
    return jObj;/*from  www .  j a  v a2s.  c  o m*/
}

From source file:angularBeans.util.CommonUtils.java

License:LGPL

public static JsonElement parse(String message) {

    if (!message.startsWith("{")) {
        return new JsonPrimitive(message);
    }//from w  w w  .  j  av  a 2  s  .c  o  m
    JsonParser parser = new JsonParser();
    return parser.parse(message);
}

From source file:apim.restful.importexport.utils.APIExportUtil.java

License:Open Source License

/**
 * Retrieve meta information of the API to export
 * URL template information are stored in swagger.json definition while rest of the required
 * data are in api.json//from   ww  w.j a v a 2s  . c om
 *
 * @param apiToReturn API to be exported
 * @param registry    Current tenant registry
 * @throws APIExportException If an error occurs while exporting meta information
 */
private static void exportMetaInformation(API apiToReturn, Registry registry) throws APIExportException {
    APIDefinition definitionFromSwagger20 = new APIDefinitionFromSwagger20();
    String archivePath = archiveBasePath
            .concat(File.separator + apiToReturn.getId().getApiName() + "-" + apiToReturn.getId().getVersion());

    createDirectory(archivePath + File.separator + "Meta-information");
    //Remove unnecessary data from exported Api
    cleanApiDataToExport(apiToReturn);

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String apiInJson = gson.toJson(apiToReturn);
    writeFile(archivePath + File.separator + "Meta-information" + File.separator + "api.json", apiInJson);

    try {
        String swaggerDefinition = definitionFromSwagger20.getAPIDefinition(apiToReturn.getId(), registry);
        JsonParser parser = new JsonParser();
        JsonObject json = parser.parse(swaggerDefinition).getAsJsonObject();
        String formattedSwaggerJson = gson.toJson(json);
        writeFile(archivePath + File.separator + "Meta-information" + File.separator + "swagger.json",
                formattedSwaggerJson);

        if (log.isDebugEnabled()) {
            log.debug("Meta information retrieved successfully");
        }

    } catch (APIManagementException e) {
        log.error("Error while retrieving Swagger definition" + e.getMessage());
        throw new APIExportException("Error while retrieving Swagger definition", e);
    }
}

From source file:asteroidtracker.AsteroidTrackerSpeechlet.java

License:Open Source License

/**
 * Parse JSON-formatted list of events/births/deaths from Wikipedia, extract list of events and
 * split the events into a String array of individual events. Run Regex matchers to make the
 * list pretty by adding a comma after the year to add a pause, and by removing a unicode char.
 * //from  w  w w. j a  v  a 2  s. c  o  m
 * @param text
 *            the JSON formatted list of events/births/deaths for a certain date
 * @return String array of events for that date, 1 event per element of the array
 */
private ArrayList<String> parseJson(String text, String date) {
    ArrayList<String> events = new ArrayList<String>();

    if (text.isEmpty()) {
        return events;
    }
    JsonParser parser = new JsonParser();
    JsonObject object = parser.parse(text).getAsJsonObject();

    JsonArray asteroidArray = object.get("near_earth_objects").getAsJsonObject().get(date).getAsJsonArray();

    for (int i = 0; i < object.get("element_count").getAsInt(); i++) {
        JsonObject thisAsteroid = asteroidArray.get(i).getAsJsonObject();

        String asteroidName = thisAsteroid.get("name").getAsString();

        float absoluteMagnitude = thisAsteroid.get("absolute_magnitude_h").getAsFloat();

        JsonObject estimatedDiameterKilometers = thisAsteroid.get("estimated_diameter").getAsJsonObject()
                .get("kilometers").getAsJsonObject();
        float minimumDiameter = estimatedDiameterKilometers.get("estimated_diameter_min").getAsFloat();
        float maximumDiameter = estimatedDiameterKilometers.get("estimated_diameter_max").getAsFloat();

        boolean isDangerousObject = thisAsteroid.get("is_potentially_hazardous_asteroid")
                .getAsString() == "false";

        JsonObject closeApproachData = thisAsteroid.get("close_approach_data").getAsJsonArray().get(0)
                .getAsJsonObject();
        float speed = closeApproachData.get("relative_velocity").getAsJsonObject().get("kilometers_per_hour")
                .getAsFloat();
        Number missDistance = closeApproachData.get("miss_distance").getAsJsonObject().get("kilometers")
                .getAsNumber();
        String orbitingBody = closeApproachData.get("orbiting_body").getAsString();

        DecimalFormat df = new DecimalFormat("#.##");

        String asteroidIdText = "Asteroid " + i + ", name is " + asteroidName + ",";
        String magnitudeText = "The absolute magnitude is " + absoluteMagnitude;
        String sizeText = ", the estimated diameter is from " + df.format(minimumDiameter) + " to "
                + df.format(maximumDiameter) + " kilometers,";

        String dangerousnessText;
        if (isDangerousObject) {
            dangerousnessText = "This object is dangerous!";
        } else {
            dangerousnessText = "This object is not dangerous,";
        }

        String speedText = "It is traveling at " + df.format(speed) + " kilometers per hour";
        String distanceText = " at a distance of " + missDistance + " kilometers";
        String orbitingBodyText = " and is orbiting " + orbitingBody;

        String eventText = asteroidIdText + magnitudeText + sizeText + dangerousnessText + speedText
                + distanceText + orbitingBodyText;
        events.add(eventText);
    }

    return events;
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.json.JsonMapperImpl.java

License:Apache License

@Override
public <K> K deserialize(String serializedObject, Class<K> targetClass) {
    JsonParser parser = new JsonParser();
    JsonObject jsonObject = (JsonObject) parser.parse(serializedObject);
    K object = ReflectionUtil.createInstance(targetClass);
    ObjectNavigator objectNavigator = new ObjectNavigatorImpl(typeAdapterFactory);
    Visitor visitor = new JsonDeserializationVisitor(jsonObject, object);
    objectNavigator.navigate(object, visitor);
    return object;
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.hbase.HbaseListTypeAdapter.java

License:Apache License

@Override
public List<?> deserialize(HbaseCell element, TypeMetadata<HbaseCell> typeMetadata) {
    String jsonString = Bytes.toString(element.getValue());
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonString);
    TypeMetadata<JsonElement> jsonTypeMetadata = new TypeMetadataImpl(typeMetadata,
            ReflectionUtil.getFieldByName(typeMetadata.getParent(), typeMetadata.getFieldName()),
            new JsonTypeAdapterFactory(), JsonElement.class);
    return new JsonListTypeAdapter().deserialize(jsonElement, jsonTypeMetadata);
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.hbase.HbaseMapTypeAdapter.java

License:Apache License

@Override
public Map<?, ?> deserialize(HbaseCell element, TypeMetadata<HbaseCell> typeMetadata) {
    String jsonString = Bytes.toString(element.getValue());
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonString);
    TypeMetadata<JsonElement> jsonTypeMetadata = new TypeMetadataImpl(typeMetadata,
            ReflectionUtil.getFieldByName(typeMetadata.getParent(), typeMetadata.getFieldName()),
            new JsonTypeAdapterFactory(), JsonElement.class);
    return new JsonMapTypeAdapter().deserialize(jsonElement, jsonTypeMetadata);
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.hbase.HbaseTypeParameterTypeAdapter.java

License:Apache License

@Override
public Object deserialize(HbaseCell element, TypeMetadata<HbaseCell> typeMetadata) {
    String jsonString = Bytes.toString(element.getValue());
    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(jsonString);
    TypeMetadata<JsonElement> jsonTypeMetadata = new TypeMetadataImpl(typeMetadata,
            ReflectionUtil.getFieldByName(typeMetadata.getParent(), typeMetadata.getFieldName()),
            new JsonTypeAdapterFactory(), JsonElement.class);
    return new JsonMapTypeAdapter().deserialize(jsonElement, jsonTypeMetadata);
}