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:bmw.assigment.BMWAssigment.java

/**
 * For this reading I used GSON, a library made by google to parse JSON objects
 * In order for this to run propertly, a file employees.json must be in the path /resources/employees.json
 * /*from  www.j a  va  2  s.  c o m*/
 * @return JsonObject
 */
public JsonObject readJsonFile() {

    JsonObject employeeRoot = null;

    try {
        InputStream str = BMWAssigment.class.getResourceAsStream("/resources/employees.json");
        JsonReader reader = new JsonReader(new InputStreamReader(str));
        JsonParser jsonParser = new JsonParser();
        employeeRoot = jsonParser.parse(reader).getAsJsonObject();

        reader.close();
        str.close();

    } catch (IOException ex) {
        Logger.getLogger(BMWAssigment.class.getName()).log(Level.SEVERE, null, ex);
    }

    return employeeRoot;
}

From source file:br.com.anteros.social.facebook.utils.JsonUtils.java

License:Apache License

public static <T> T fromJson(String json, Class<T> cls) {
    Gson gson = buildGson();/*ww  w  . ja v a 2 s  . c o m*/

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

    if (cls != null && cls.isArray() && element instanceof JsonArray == false) {
        JsonArray jsonArray = new JsonArray();
        jsonArray.add(element);

        Type listType = new TypeToken<T>() {
        }.getType();
        return gson.fromJson(jsonArray, listType);
    }

    return gson.fromJson(json, cls);
}

From source file:br.com.anteros.social.facebook.utils.JsonUtils.java

License:Apache License

public static <T> T fromJson(String json, Type type) {
    Gson gson = buildGson();/*from   w w  w. ja v a  2  s.  c  o m*/

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

    return gson.fromJson(element, type);
}

From source file:br.com.anteros.social.facebook.utils.JsonUtils.java

License:Apache License

public static <T> T fromJsonExcludeFields(String json, Class<T> cls) {
    Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();

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

    if (cls.isArray() && element instanceof JsonArray == false) {
        JsonArray jsonArray = new JsonArray();
        jsonArray.add(element);//from  ww  w . j av  a 2  s .  com

        Type listType = new TypeToken<T>() {
        }.getType();
        return gson.fromJson(jsonArray, listType);
    }

    return gson.fromJson(json, cls);
}

From source file:br.com.caelum.vraptor.serialization.gson.GsonDeserialization.java

License:Open Source License

@Override
public Object[] deserialize(InputStream inputStream, ControllerMethod method) {
    Class<?>[] types = getTypes(method);

    if (types.length == 0) {
        throw new IllegalArgumentException(
                "Methods that consumes representations must receive just one argument");
    }//from w w  w. ja  v  a2s. c om

    Gson gson = builder.create();

    final Parameter[] parameterNames = paramNameProvider.parametersFor(method.getMethod());
    final Object[] values = new Object[parameterNames.length];
    final Deserializee deserializee = deserializeeInstance.get();

    try {
        String content = getContentOfStream(inputStream);
        logger.debug("json retrieved: {}", content);

        if (!isNullOrEmpty(content)) {
            JsonParser parser = new JsonParser();
            JsonElement jsonElement = parser.parse(content);
            if (jsonElement.isJsonObject()) {
                JsonObject root = jsonElement.getAsJsonObject();

                deserializee.setWithoutRoot(isWithoutRoot(parameterNames, root));

                for (Class<? extends DeserializerConfig> option : method.getMethod()
                        .getAnnotation(Consumes.class).options()) {
                    DeserializerConfig config = container.instanceFor(option);
                    config.config(deserializee);
                }

                for (int i = 0; i < types.length; i++) {
                    Parameter parameter = parameterNames[i];
                    JsonElement node = root.get(parameter.getName());

                    if (deserializee.isWithoutRoot()) {
                        values[i] = gson.fromJson(root, fallbackTo(parameter.getParameterizedType(), types[i]));
                        logger.info("json without root deserialized");
                        break;

                    } else if (node != null) {
                        if (node.isJsonArray()) {
                            JsonArray jsonArray = node.getAsJsonArray();
                            Type type = parameter.getParameterizedType();
                            if (type instanceof ParameterizedType) {
                                values[i] = gson.fromJson(jsonArray, type);
                            } else {
                                values[i] = gson.fromJson(jsonArray, types[i]);
                            }
                        } else {
                            values[i] = gson.fromJson(node, types[i]);
                        }
                    }
                }
            } else if (jsonElement.isJsonArray()) {
                if ((parameterNames.length != 1)
                        || (!(parameterNames[0].getParameterizedType() instanceof ParameterizedType)))
                    throw new IllegalArgumentException(
                            "Methods that consumes an array representation must receive only just one collection generic typed argument");

                JsonArray jsonArray = jsonElement.getAsJsonArray();
                values[0] = gson.fromJson(jsonArray, parameterNames[0].getParameterizedType());
            } else {
                throw new IllegalArgumentException("This is an invalid or not supported json content");
            }
        }
    } catch (Exception e) {
        throw new ResultException("Unable to deserialize data", e);
    }

    logger.debug("json deserialized: {}", (Object) values);
    return values;
}

From source file:br.com.davimonteiro.lotus_runtime.config.ConfigurationUtil.java

License:Open Source License

public static Configuration save(Path configPath, Configuration config) {
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.setPrettyPrinting().create();

    JsonParser parser = new JsonParser();
    JsonElement jsonElement = parser.parse(gson.toJson(config));

    String json = gson.toJson(jsonElement);

    try {// w w  w.  java2 s .  co  m
        Files.write(configPath, json.getBytes());
    } catch (IOException e) {
        e.printStackTrace();
    }

    return config;
}

From source file:br.com.rednetsolucoes.merendaescolar.serviceimpl.MerendaEscolaServiceImpl.java

@Override
public List<MerendaEscola> listarEscolas() {
    String uri = "http://localhost:8080/webresources/escolaservice";

    WebTarget webTarget = ClientBuilder.newClient().target(uri);
    String entity = webTarget.request().get().readEntity(String.class);

    List<MerendaEscola> escolas = new ArrayList<>();

    JsonParser parser = new JsonParser();
    JsonArray jsonArray = parser.parse(entity).getAsJsonArray();
    for (JsonElement j : jsonArray) {
        String nomeEscola = j.getAsJsonObject().get("nome").toString();
        long idEscola = j.getAsJsonObject().get("id").getAsLong();

        escolas.add(new MerendaEscola(new MerendaEstoque(), nomeEscola, idEscola));
    }//www.  j av a  2s  . c o  m

    return escolas;
}

From source file:br.com.rednetsolucoes.merendaescolar2.serviceimpl.EscolaEstoqueServiceImpl.java

@Override
public List<EscolaEstoque> listarEscolas() {
    String uri = "http://localhost:8080/webresources/escolaservice";

    WebTarget webTarget = ClientBuilder.newClient().target(uri);
    String entity = webTarget.request().get().readEntity(String.class);

    List<EscolaEstoque> escolas = new ArrayList<>();

    JsonParser parser = new JsonParser();
    JsonArray jsonArray = parser.parse(entity).getAsJsonArray();
    for (JsonElement j : jsonArray) {
        String nomeEscola = j.getAsJsonObject().get("nome").toString();
        long idEscola = j.getAsJsonObject().get("id").getAsLong();

        escolas.add(new EscolaEstoque(nomeEscola, idEscola, new ArrayList()));
    }//from  w w w.  j  a v  a 2  s . co m

    return escolas;
}

From source file:br.com.uft.scicumulus.utils.Utils.java

public static JsonObject openFileJson(String file) throws FileNotFoundException {
    FileReader reader = new FileReader(file);
    JsonParser jsonParser = new JsonParser();
    JsonObject jsonObject = (JsonObject) jsonParser.parse(reader);
    return jsonObject;
}

From source file:br.mack.api.Marvel.java

public static void main(String[] args) {
    //Criao de um timestamp
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("MMddyyyyhhmmss");
    String ts = sdf.format(date);

    //Criao do HASH
    String hashStr = MD5(ts + privatekey + apikey);
    String uri;/*from  w  ww .j a  v a 2  s. co  m*/
    String name = "Captain%20America";
    //url de consulta
    uri = urlbase + "?nameStartsWith=" + name + "&ts=" + ts + "&apikey=" + apikey + "&hash=" + hashStr;

    try {
        CloseableHttpClient cliente = HttpClients.createDefault();

        //HttpHost proxy = new HttpHost("172.16.0.10", 3128, "http");
        //RequestConfig config = RequestConfig.custom().setProxy(proxy).build();
        HttpGet httpget = new HttpGet(uri);
        //httpget.setConfig(config);
        HttpResponse response = cliente.execute(httpget);
        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        //Header[] h = (Header[]) response.getAllHeaders();

        /*for (Header head : h) {
        System.out.println(head.getValue());
        }*/
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
            StringBuilder out = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                out.append(line);
            }
            //System.out.println(out.toString());
            reader.close();
            instream.close();
            JsonParser parser = new JsonParser();

            // find character's comics
            JsonElement comicResultElement = parser.parse(out.toString());
            JsonObject comicDataWrapper = comicResultElement.getAsJsonObject();
            JsonObject data = (JsonObject) comicDataWrapper.get("data");
            JsonArray results = data.get("results").getAsJsonArray();

            System.out.println(((JsonObject) results.get(0)).get("thumbnail"));

        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}