Example usage for com.google.gson GsonBuilder create

List of usage examples for com.google.gson GsonBuilder create

Introduction

In this page you can find the example usage for com.google.gson GsonBuilder create.

Prototype

public Gson create() 

Source Link

Document

Creates a Gson instance based on the current configuration.

Usage

From source file:com.ab.util.AbJsonUtil.java

License:Apache License

/**
 * //from   w w  w.  j a  v a2  s. c  o  m
 * ??json.
 * @param list
 * @return
 */
public static String toJson(List<?> list) {
    String json = null;
    try {
        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        json = gson.toJson(list);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return json;
}

From source file:com.ab.util.AbJsonUtil.java

License:Apache License

/**
 * //from www . j  av a  2 s . co m
 * ??json.
 * @param json
 * @param typeToken new TypeToken<ArrayList<?>>() {};
 * @return
 */
public static List<?> fromJson(String json, TypeToken typeToken) {
    List<?> list = null;
    try {
        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        Type type = typeToken.getType();
        list = gson.fromJson(json, type);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}

From source file:com.ab.util.AbJsonUtil.java

License:Apache License

/**
 * /*w  w w. ja va2s  . c  o m*/
 * ??json.
 * @param json
 * @param clazz
 * @return
 */
public static Object fromJson(String json, Class clazz) {
    Object obj = null;
    try {
        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        obj = gson.fromJson(json, clazz);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return obj;
}

From source file:com.actionml.entity.Event.java

License:Apache License

@Override
public String toString() {
    // handle DateTime separately
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeAdapter());
    Gson gson = gsonBuilder.create();
    return gson.toJson(this); // works when there are no generic types
}

From source file:com.addhen.voto.sdk.BaseApiBuilder.java

License:Apache License

private void initializeGson() {
    GsonBuilder builder = new GsonBuilder();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    builder.registerTypeAdapter(Date.class, new DateDeserializer());
    mGson = builder.create();
}

From source file:com.aelitis.azureus.util.JSONUtilsGSON.java

License:Open Source License

private static Gson getGson() {
    if (gson == null) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapterFactory(ObjectTypeAdapterLong.FACTORY);
        gson = builder.create();
    }//from  www  .  j  a v  a2  s.  c  o m
    return gson;
}

From source file:com.algodefu.yeti.web.ClusterServlet.java

License:Apache License

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/json");
    response.setHeader("Cache-Control", "nocache");
    response.setCharacterEncoding("utf-8");
    PrintWriter out = response.getWriter();
    ClusterFormat clusterFormat = new ClusterFormat();

    // for JSON//  ww  w  .  ja va 2 s.  c  om
    String errMsg = "";
    String clusterTitle = "";
    List<Cluster> clusterData = new ArrayList<>();
    String symbol = "";

    try {
        symbol = request.getParameter("symbol");
        int count = Integer.parseInt(request.getParameter("count"));
        LocalDateTime beginDt = LocalDateTime.parse(request.getParameter("beginDt"), dtf);
        LocalDateTime endDt = LocalDateTime.parse(request.getParameter("endDt"), dtf);

        ClusterType clusterType = ClusterType.fromName(request.getParameter("cluster-type"));
        clusterFormat.setType(clusterType);
        clusterFormat.setSymbol(symbol);
        clusterFormat.setBeginDt(beginDt);
        clusterFormat.setEndDt(endDt);
        clusterFormat.setCount(count);

        switch (clusterType) {
        case TIMEFRAME:
        case TICKTIME:
            int timeInterval = Integer.parseInt(request.getParameter("time-interval"));
            ChronoUnit chronoUnit = ChronoUnit.valueOf(request.getParameter("chronoUnit"));
            clusterFormat.setTimeInterval(timeInterval);
            clusterFormat.setChronoUnit(chronoUnit);
            break;
        case PRICERANGE:
            double priceRange = Double.parseDouble(request.getParameter("price-range"));
            clusterFormat.setPriceRange(priceRange);
            break;
        case VOLUME:
            long clusterVolume = Long.parseLong(request.getParameter("cluster-volume"));
            clusterFormat.setClusterVolume(clusterVolume);
            break;
        case TRADECOUNT:
            long maxTicksInCluster = Long.parseLong(request.getParameter("maxNumTicksInCluster"));
            clusterFormat.setMaxTicksInCluster(maxTicksInCluster);
            break;
        }

        ClusterSource clusterSource = new ClusterSource(clusterFormat);
        Instant start = Instant.now();
        clusterData = clusterSource.getClusters();
        Instant stop = Instant.now();
        System.out.printf("%d clusters of type %s generated in %d ms. \n", clusterData.size(),
                clusterFormat.getType().toString(), Duration.between(start, stop).toMillis());

        // add clusterType as title
        if (clusterFormat.getType() != null)
            clusterTitle = clusterFormat.getType().toString() + " CLUSTERS";

    } catch (Exception e) {
        errMsg = e.toString().replace("\"", " ");
        e.printStackTrace();
    }

    Hashtable<String, Object> hashtable = new Hashtable<>();
    hashtable.put("errMsg", errMsg);
    hashtable.put("symbol", symbol);
    hashtable.put("clusterTitle", clusterTitle);
    hashtable.put("clusterData", clusterData.toArray());

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Cluster.class, new ClusterTypeAdapter());
    Gson gson = gsonBuilder.create();

    out.println(gson.toJson(hashtable));
    out.flush();
    out.close();
}

From source file:com.algodefu.yeti.web.ShowTradeInPassServlet.java

License:Apache License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String reqTradeId = request.getParameter("tradeId");
    String reqPassId = request.getParameter("passId");
    String reqShowAllTrades = request.getParameter("showAllTrades");
    String reqStartTradeId = request.getParameter("startTradeId");
    String reqEndTradeId = request.getParameter("endTradeId");

    // for JSON/*from   www.ja v a  2s  .  c  o  m*/
    String errMsg = "";
    String symbol = "";
    String clusterTitle = "";
    List<Cluster> clusterData = new ArrayList<>();

    boolean forwardReq = false;

    if (reqPassId == null || reqPassId.trim().isEmpty())
        forwardReq = true;

    if (forwardReq) {
        // show input passId form
        RequestDispatcher view = request.getRequestDispatcher("/formpassid.html");
        view.forward(request, response);
    } else {
        response.setHeader("Cache-Control", "nocache");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        long singleTradeId = 0;
        long startTradeId = 0;
        long endTradeId = 0;
        int showAllTrades = 0;

        try {
            if (!reqTradeId.equals("undefined") && reqTradeId != null && !reqTradeId.trim().isEmpty())
                singleTradeId = Long.parseLong(reqTradeId);

            if (!reqStartTradeId.equals("undefined") && reqStartTradeId != null
                    && !reqStartTradeId.trim().isEmpty())
                startTradeId = Long.parseLong(reqStartTradeId);

            if (!reqEndTradeId.equals("undefined") && reqEndTradeId != null && !reqEndTradeId.trim().isEmpty())
                endTradeId = Long.parseLong(reqEndTradeId);

            if (!reqShowAllTrades.equals("undefined") && reqShowAllTrades != null
                    && !reqShowAllTrades.trim().isEmpty())
                showAllTrades = Integer.parseInt(reqShowAllTrades);

            TaskStorage taskStorage = TaskStorage.getInstance();

            // find the required trade / trades
            Trade[] trades = taskStorage.getTradesByPassId(reqPassId);

            if (showAllTrades != 1) {
                List<Trade> tradeList = new ArrayList<>();

                for (Trade t : trades) {
                    if (singleTradeId > 0 && t.getTradeID() == singleTradeId) {
                        tradeList.add(t);
                        break;
                    } else if (startTradeId > 0 && endTradeId > 0 && t.getTradeID() >= startTradeId
                            && t.getTradeID() <= endTradeId) {
                        tradeList.add(t);
                    }
                }

                trades = tradeList.toArray(new Trade[0]);
            }

            // get deals for each trade
            List<Deal> deals = new ArrayList<>();
            List<Deal> tempDeals = new ArrayList<>();
            for (Trade t : trades) {
                tempDeals = t.getDeals();
                for (int i = 0; i < tempDeals.size(); i++) {
                    if (tempDeals.get(i).getOrder() != OrderType.CANCELLED)
                        deals.add(tempDeals.get(i));
                }
            }

            ClusterFormat clusterFormat = taskStorage.getStrategyParamSetByPassId(reqPassId).getClusterFormat();
            symbol = clusterFormat.getSymbol();
            ClusterSource clusterSource = new ClusterSource(clusterFormat);
            List<Cluster> clusterList = clusterSource.getClusters();

            int startClusterIndex = 0;
            int endClusterIndex = 0;
            int tempClusterIndex = 0;

            for (Deal deal : deals) {
                Cluster cluster = null;
                for (int i = 0; i < clusterList.size(); i++) {
                    cluster = clusterList.get(i);
                    if (deal.getDateTime().compareTo(cluster.getOpenDateTime()) >= 0
                            && deal.getDateTime().compareTo(cluster.getCloseDateTime()) <= 0) {
                        if (deal.getEntry() == DealEntry.IN) {
                            cluster.addDeal(deal);
                            tempClusterIndex = i - 20;

                            if (tempClusterIndex < 0)
                                tempClusterIndex = 0;

                            if (startClusterIndex == 0)
                                startClusterIndex = tempClusterIndex;

                            if (tempClusterIndex < startClusterIndex)
                                startClusterIndex = tempClusterIndex;

                            //                                if(tempClusterIndex > 0 && (startClusterIndex > 0 && tempClusterIndex < startClusterIndex))
                            //                                    startClusterIndex = tempClusterIndex;

                            break;
                        }

                        if (deal.getEntry() == DealEntry.OUT && deal.getPrice() >= cluster.getLow()
                                && deal.getPrice() <= cluster.getHigh()) {
                            cluster.addDeal(deal);
                            tempClusterIndex = i + 1;

                            if (tempClusterIndex > clusterList.size() - 1)
                                tempClusterIndex = clusterList.size() - 1;

                            if (endClusterIndex == 0)
                                endClusterIndex = tempClusterIndex;

                            if (tempClusterIndex > endClusterIndex)
                                endClusterIndex = tempClusterIndex;

                            //                                if(tempClusterIndex > 0 && tempClusterIndex < clusterList.size() - 1 &&
                            //                                        (endClusterIndex >= 0 && tempClusterIndex > endClusterIndex))
                            //                                    endClusterIndex = tempClusterIndex;

                            break;
                        }
                    }
                } // end for clusterList
            } // end for - deal

            // add clusterType as title
            if (clusterFormat.getType() != null)
                clusterTitle = clusterFormat.getType().toString() + " CLUSTERS";

            // add clusterData
            for (int i = startClusterIndex; i <= endClusterIndex; i++) {
                clusterData.add(clusterList.get(i));
            }

        } catch (Exception e) {
            errMsg = e.toString();
            e.printStackTrace();
        }

        Hashtable<String, Object> hashtable = new Hashtable<>();
        hashtable.put("errMsg", errMsg);
        hashtable.put("symbol", symbol);
        hashtable.put("clusterTitle", clusterTitle);
        hashtable.put("clusterData", clusterData.toArray());

        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Cluster.class, new ClusterTypeAdapter());
        Gson gson = gsonBuilder.create();

        out.println(gson.toJson(hashtable));
        out.flush();
        out.close();
    }

}

From source file:com.ali.truyentranh.activity.CategoryActivity.java

License:Apache License

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.home_favorite);
    context = this;

    tvShowsGridView = (MyGridView) findViewById(R.id.gv_tv_shows);

    Intent intent = getIntent();/*from w w  w.j  av  a2  s . co m*/
    String value = intent.getStringExtra("category");
    final GsonBuilder gsonBuilder = new GsonBuilder();
    Gson gson = gsonBuilder.create();
    api = "http://comicvn.net/truyentranh/apiv2/theloai?id=";
    Category category = gson.fromJson(value, Category.class);
    api = api + category.getId();
    setTitle(category.getName());

    adapter = new GridMangaAdapter(CategoryActivity.context, null, api);
    tvShowsGridView.setAdapter(adapter);
    tvShowsGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            Manga item = (Manga) adapter.getItem(position);
            Intent myIntent = new Intent(CategoryActivity.context, DetailActivity.class);
            myIntent.putExtra("detail", item.toString());
            CategoryActivity.context.startActivity(myIntent);
        }
    });

    scrollView = (ObservableScrollView) findViewById(R.id.scrollview);
    scrollView.setScrollViewListener(this);

    //Get a Tracker (should auto-report)
    Tracker t = ((Analytics) getApplication()).getTracker(Analytics.TrackerName.APP_TRACKER);
    t.setScreenName("Category");
    t.send(new HitBuilders.AppViewBuilder().build());
}

From source file:com.aliakseipilko.flightdutytracker.dagger.modules.GsonModule.java

License:Open Source License

@Provides
public Gson provideGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
    return gsonBuilder.create();
}