Example usage for com.google.gson.reflect TypeToken getType

List of usage examples for com.google.gson.reflect TypeToken getType

Introduction

In this page you can find the example usage for com.google.gson.reflect TypeToken getType.

Prototype

public final Type getType() 

Source Link

Document

Gets underlying Type instance.

Usage

From source file:com.vko.core.common.util.gson.GsonUtil.java

License:Apache License

/**
 *  {@code JSON} ??/* w w w. j av  a 2  s .c o m*/
 * 
 * @param <T>
 *            ??
 * @param json
 *             {@code JSON} 
 * @param token
 *            {@code com.google.gson.reflect.TypeToken} 
 * @param datePattern
 *            ??
 * @return  {@code JSON} 
 * @since 1.0
 */
public static <T> T fromJson(String json, TypeToken<T> token, String datePattern) {
    if (StringUtils.isBlank(json)) {
        return null;
    }
    GsonBuilder builder = new GsonBuilder();
    if (StringUtils.isBlank(datePattern)) {
        datePattern = DEFAULT_DATE_PATTERN;
    }
    Gson gson = builder.create();
    try {
        return (T) gson.fromJson(json, token.getType());
    } catch (Exception ex) {
        LOGGER.error(json + " ? " + token.getRawType().getName() + " !", ex);
        return null;
    }
}

From source file:com.zekke.services.http.JsonRequestBuilder.java

License:Apache License

public <T> T callForResult(TypeToken<T> resultType) throws RequestException {
    String json = null;//  w ww  .j  a  va  2  s  .c  o  m
    try {
        setUpHeaders();
        setUpFormParams();
        Log.d(TAG, "URL: " + request.getURI());
        HttpResponse response = httpClient.execute(request);
        Log.d(TAG, "Status code: " + response.getStatusLine().getStatusCode());
        HttpEntity entity = response.getEntity();
        json = entity != null ? EntityUtils.toString(entity, HTTP.UTF_8) : null;
        if ((response.getStatusLine().getStatusCode() == HttpStatus.SC_OK
                || response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED)
                && !StringUtils.isNullOrBlank(json)) {
            return new Gson().fromJson(json, resultType.getType());
        }
    } catch (ClientProtocolException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.http_protocol_error).setErrorType(ex)
                .build();
    } catch (SocketTimeoutException ex) {
        Log.e(TAG, "Timeout", ex);
        throw new RequestException.Builder().setMessageResource(R.string.timeout_error).setErrorType(ex)
                .build();
    } catch (ConnectTimeoutException ex) {
        Log.e(TAG, "Timeout", ex);
        throw new RequestException.Builder().setMessageResource(R.string.timeout_error).setErrorType(ex)
                .build();
    } catch (UnsupportedEncodingException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.params_encoding_error).setErrorType(ex)
                .build();
    } catch (IOException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                .build();
    } catch (JsonSyntaxException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                .build();
    } catch (ParseException ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.parse_response_error).setErrorType(ex)
                .build();
    } catch (Exception ex) {
        Log.e(TAG, "Developer bug :(", ex);
        throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                .build();
    }

    if (!StringUtils.isNullOrBlank(json)) {
        try {
            Log.e(TAG, "Server error: " + json);
            throw new Gson().fromJson(json, RequestException.class);
        } catch (JsonSyntaxException ex) {
            throw new RequestException.Builder().setMessageResource(R.string.unknown_error).setErrorType(ex)
                    .build();
        }
    }

    return null;
}

From source file:contra.AddUpdateContraVoucher.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w . ja v a 2s .  com*/
 *
 * @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 String detailJson = request.getParameter("detail");
    TypeToken<List<ContraVoucherModel>> token = new TypeToken<List<ContraVoucherModel>>() {
    };
    List<ContraVoucherModel> detail = new Gson().fromJson(detailJson, token.getType());
    response.getWriter().print(saveVoucher((ArrayList<ContraVoucherModel>) detail));

}

From source file:DC.AddUpdateDCDetail.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*ww  w . ja v  a2s. c  o  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 String detailJson = request.getParameter("detail");
    TypeToken<List<SalesBillDetail>> token = new TypeToken<List<SalesBillDetail>>() {
    };
    List<SalesBillDetail> detail = new Gson().fromJson(detailJson, token.getType());
    response.getWriter().print(saveVoucher((ArrayList<SalesBillDetail>) detail));

}

From source file:de.anycook.einkaufszettel.tasks.LoadRecipesTask.java

License:Open Source License

@Override
protected List<RecipeResponse> doInBackground(Void... b) {
    try {//from ww w  .jav  a  2s.  c om
        LOGGER.d("Trying to load recipes from %s", url);

        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

        if (sharedPreferences.contains("last-modified-recipes") && !emptyRecipes) {
            httpURLConnection.setRequestProperty("If-Modified-Since",
                    sharedPreferences.getString("last-modified-recipes", null));
        }

        if (httpURLConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            throw new IOException(httpURLConnection.getResponseMessage());
        }

        String newLastModified = httpURLConnection.getHeaderField("last-modified");
        if (newLastModified != null) {
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("last-modified-recipes", newLastModified);
            editor.apply();
        }

        Reader reader = new InputStreamReader(httpURLConnection.getInputStream());
        Gson gson = new Gson();
        TypeToken<ArrayList<RecipeResponse>> typeToken = new TypeToken<ArrayList<RecipeResponse>>() {
        };
        return gson.fromJson(reader, typeToken.getType());
    } catch (IOException e) {
        LOGGER.e("failed to load recipes from " + url, e);
        return Collections.emptyList();
    }
}

From source file:de.clemensbartz.jtwitchstreamsapi.util.network.JSONRequestor.java

License:Apache License

public synchronized static <T> T requestJSONForTypeToken(URL url, TypeToken<T> clazz) throws IOException {
    return new Gson().fromJson(JSONRequestor.getContent(url), clazz.getType());
}

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

License:Apache License

@Override
public IfmapGraphImpl deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) {
    IfmapGraphImpl graph = new IfmapGraphImpl();
    TypeToken<HashMap<String, JsonElement>> hashMapType = new TypeToken<HashMap<String, JsonElement>>() {
    };/*from w  w w .java 2s. c o m*/
    HashMap<String, JsonElement> jsonGraph = GSON.fromJson(json, hashMapType.getType());
    graph.setLastUpdated(jsonGraph.get("timestamp").getAsLong());
    JsonArray jsonLinkList = jsonGraph.get("links").getAsJsonArray();

    // Iterate over all link items, i.e. entries of identifier(s) and their
    // metadata
    for (JsonElement jsonLink : jsonLinkList) {
        HashMap<String, JsonElement> jsonItem = GSON.fromJson(jsonLink, hashMapType.getType());

        // Either we have two identifiers with a link that contains metadata
        if (jsonItem.get("identifiers").isJsonArray()) {
            JsonArray jsonIdentifierList = jsonItem.get("identifiers").getAsJsonArray();
            IfmapVertex identifierOne = ifmapVertexFromJson(jsonIdentifierList.get(0));
            IfmapVertex identifierTwo = ifmapVertexFromJson(jsonIdentifierList.get(1));
            IfmapVertex existingIdentifierOne = findVertex(identifierOne, graph);
            IfmapVertex existingIdentifierTwo = findVertex(identifierTwo, graph);
            if (existingIdentifierOne == null) {
                graph.addVertex(identifierOne);
            } else {
                identifierOne = existingIdentifierOne;
            }
            if (existingIdentifierTwo == null) {
                graph.addVertex(identifierTwo);
            } else {
                identifierTwo = existingIdentifierTwo;
            }

            if (jsonItem.get("metadata") != null) {
                // More than 1 metadatum
                if (jsonItem.get("metadata").isJsonArray()) {
                    JsonArray jsonMetadataList = jsonItem.get("metadata").getAsJsonArray();
                    for (JsonElement jsonMetadata : jsonMetadataList) {
                        Metadata meta = metadataFromJson(jsonMetadata);
                        IfmapEdgeImpl edge = new IfmapEdgeImpl(identifierOne, identifierTwo, meta);
                        graph.addEdgeSensitive(identifierOne, identifierTwo, edge);
                    }
                    // Exactly one connected metadatum
                } else {
                    Metadata meta = metadataFromJson(jsonItem.get("metadata"));
                    IfmapEdgeImpl edge = new IfmapEdgeImpl(identifierOne, identifierTwo, meta);
                    edge.setMetadata(meta);
                    graph.addEdgeSensitive(identifierOne, identifierTwo, edge);
                }
            }

            // ... or we have a single identifier with metadata attached to
        } else {
            IfmapVertex identifier = ifmapVertexFromJson(jsonItem.get("identifiers"));
            IfmapVertex existingIdentifier = findVertex(identifier, graph);
            if (existingIdentifier == null) {
                graph.addVertex(identifier);
            } else {
                identifier = existingIdentifier;
            }

            if (jsonItem.get("metadata") != null) {
                // More than 1 metadatum
                if (jsonItem.get("metadata").isJsonArray()) {
                    JsonArray jsonMetadataList = jsonItem.get("metadata").getAsJsonArray();
                    for (JsonElement jsonMetadata : jsonMetadataList) {
                        Metadata meta = metadataFromJson(jsonMetadata);
                        graph.addMetadataToVertex(identifier, meta);
                        // identifier.addMetadata(meta);
                    }
                    // Exactly one connected metadatum
                } else {
                    Metadata meta = metadataFromJson(jsonItem.get("metadata"));
                    graph.addMetadataToVertex(identifier, meta);
                    // identifier.addMetadata(meta);
                }
            }
            // ... or we have broken data

        }
    }
    return graph;
}

From source file:de.mtrstudios.nflpickem.Handlers.PickEmDataHandler.java

License:Apache License

/**
 * Pulls appData from the shared preferences
 * This appData is then stored in the appData variables
 * As appData from collections is stored as a JSON String, it needs to be deserialized
 *///ww w .j a  va2  s  . c om
private void loadDataFromSharedPreferences() {
    PickEmSharedPreferences preferences = PickEmSharedPreferences.getInstance();
    Gson gson = GsonHandler.getInstance().getGson();

    // User Name and Access-Token
    this.userToken = preferences.loadString(PickEmSharedPreferences.NAME_TOKEN);
    this.userName = preferences.loadString(PickEmSharedPreferences.NAME_USERNAME);

    // Last Season Info update
    long lastUpdateMs = preferences.loadLong(PickEmSharedPreferences.NAME_LAST_SEASON_UPDATE);
    if (lastUpdateMs != 0) {
        this.lastSeasonUpdate.setTimeInMillis(lastUpdateMs);
    }

    // Last appData update
    long lastDataUpdateMs = preferences.loadLong(PickEmSharedPreferences.NAME_LAST_DATA_UPDATE);
    if (lastDataUpdateMs != 0) {
        this.lastDataUpdate.setTimeInMillis(lastUpdateMs);
    }

    // Season Info
    String jsonSeasonInfo = preferences.loadString(PickEmSharedPreferences.NAME_SEASON_INFO);
    if (!jsonSeasonInfo.equals("null")) {
        seasonInfo = gson.fromJson(jsonSeasonInfo, SeasonInfo.class);
    }

    // Games
    String jsonGames = preferences.loadString(PickEmSharedPreferences.NAME_GAMES);
    if (!jsonGames.equals("null")) {
        TypeToken<List<Game>> typeToken = new TypeToken<List<Game>>() {
        };
        games = gson.fromJson(jsonGames, typeToken.getType());
    }

    // Scores
    String jsonScores = preferences.loadString(PickEmSharedPreferences.NAME_SCORES);
    if (!jsonScores.equals("null")) {
        TypeToken<HashMap<Integer, Score>> typeToken = new TypeToken<HashMap<Integer, Score>>() {
        };
        scoresByWeek = gson.fromJson(jsonScores, typeToken.getType());
    }

    // Games/Week
    String jsonGamesPerWeek = preferences.loadString(PickEmSharedPreferences.NAME_GAMES_PER_WEEK);
    if (!jsonGamesPerWeek.equals("null")) {
        TypeToken<HashMap<Integer, Integer>> typeToken = new TypeToken<HashMap<Integer, Integer>>() {
        };
        gamesPerWeek = gson.fromJson(jsonGamesPerWeek, typeToken.getType());
    }

    // HighScores
    String jsonHighscores = preferences.loadString(PickEmSharedPreferences.NAME_HIGHSCORES);
    if (!jsonHighscores.equals("null")) {
        TypeToken<List<Highscore>> typeToken = new TypeToken<List<Highscore>>() {
        };
        highscores = gson.fromJson(jsonHighscores, typeToken.getType());
    }
}

From source file:ec.com.espe.arqui.web.AsignarRecursosBean.java

public void consultaProductosRestFul() {
    ClienteConsultaSuministros cliente = new ClienteConsultaSuministros();

    String productos = cliente.consultaPOST(this.cadenaCOnsulta, MediaType.APPLICATION_JSON.getClass());

    TypeToken<List<Producto>> token = new TypeToken<List<Producto>>() {
    };/* w  w w .jav a  2s  .  c  o  m*/
    Gson gson = new Gson();
    this.productosConsulta = gson.fromJson(productos, token.getType());
}

From source file:fr.dudie.keolis.client.JsonResponseHandler.java

License:Open Source License

public JsonResponseHandler(final TypeToken<ApiResponse<V>> responseType) {
    this.type = responseType.getType();
}