Example usage for com.google.gson GsonBuilder GsonBuilder

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

Introduction

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

Prototype

public GsonBuilder() 

Source Link

Document

Creates a GsonBuilder instance that can be used to build Gson with various configuration settings.

Usage

From source file:cmput301.f13t01.elasticsearch.ESClient.java

License:GNU General Public License

/**
 * Creates the gson object that knows how to serialize Media.
 *///from ww w  .j  av a  2 s  . c  o  m
public ESClient() {

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Media.class, new InterfaceAdapter<Media<String>>());
    gsonBuilder.registerTypeAdapter(Media.class, new InterfaceAdapter<Media<SpannableString>>());
    gsonBuilder.registerTypeAdapter(Media.class, new InterfaceAdapter<Media>());
    gson = gsonBuilder.create();

}

From source file:cmput301w15t07.TravelTracker.util.GsonIOManager.java

License:Apache License

public GsonIOManager(Context ctx) {
    this.ctx = ctx;
    gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateAdapter())
            .registerTypeAdapterFactory(new DeletionFlagTypeAdapterFactory()).serializeNulls().create();
}

From source file:cn.ieclipse.af.demo.sample.recycler.sort.SortListViewActivity.java

License:Apache License

@Override
protected void initContentView(View view) {
    super.initContentView(view);
    mSideBar = (SideBar) findViewById(R.id.contact_sidebar);
    mUserDialog = (TextView) findViewById(R.id.contact_dialog);
    mSideBar.setTextView(mUserDialog);/*from   w  w w  .  ja  v  a  2  s  . co m*/
    mSideBar.setFocusBarBackground(R.drawable.sidebar_background);

    listview = (ListView) findViewById(R.id.contact_member);
    adapter = new AtAdapter();

    Gson gson = new GsonBuilder().create();
    contactModel = gson.fromJson(DataList.tempData, ContactModel.class);
    listview.setAdapter(adapter);
    onLoadList(contactModel.lipro);

    mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

        @Override
        public void onTouchingLetterChanged(String s) {
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                listview.setSelection(position);
            }
        }
    });

}

From source file:cn.ieclipse.af.demo.sample.recycler.sort.SortRecyclerActivity.java

License:Apache License

@Override
protected void initContentView(View view) {
    super.initContentView(view);
    mSideBar = (SideBar) findViewById(R.id.contact_sidebar);
    mUserDialog = (TextView) findViewById(R.id.contact_dialog);
    mSideBar.setTextView(mUserDialog);//  w ww  . ja  va  2s.  co  m
    mSideBar.setFocusBarBackground(R.drawable.sidebar_background);

    mRefreshLayout = (RefreshLayout) view.findViewById(R.id.refresh);
    mRefreshLayout.setMode(RefreshLayout.REFRESH_MODE_NONE);
    mRefreshHelper = new RefreshRecyclerHelper<>(mRefreshLayout);

    adapter = new MyAdapter();

    headersDecor = new StickyRecyclerHeadersDecoration(adapter);
    // Header as ItemDecoration
    mRefreshHelper.setItemDecoration(headersDecor);
    // set Adapter
    mRefreshHelper.setAdapter(adapter);

    Gson gson = new GsonBuilder().create();
    contactModel = gson.fromJson(DataList.tempData, ContactModel.class);
    onLoadList(contactModel.lipro);

    mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

        @Override
        public void onTouchingLetterChanged(String s) {
            int position = adapter.getPositionForSection(s.charAt(0));
            if (position != -1) {
                // mRefreshHelper.getRecyclerView().scrollToPosition(position);
                mRefreshHelper.scrollToPosition(position);
            }
        }
    });

    adapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {
        @Override
        public void onChanged() {
            headersDecor.invalidateHeaders();
        }
    });
}

From source file:cn.taop.utils.GSONUtils.java

License:Apache License

/**
 * ????? {@code JSON} ?//from   w  ww  .j  a  v  a  2 s .c  o  m
 * <p />
 * <strong>???? <code>"{}"</code> ? <code>"[]"</code>
 * </strong>
 * 
 * @param target 
 * @param targetType 
 * @param isSerializeNulls ?? {@code null} 
 * @param version ?
 * @param datePattern ??
 * @param excludesFieldsWithoutExpose ? {@literal @Expose} 
 * @return  {@code JSON} ?
 * @since 1.0
 */
public static String toJson(Object target, Type targetType, boolean isSerializeNulls, Double version,
        String datePattern, boolean excludesFieldsWithoutExpose) {
    if (target == null)
        return EMPTY_JSON;
    GsonBuilder builder = new GsonBuilder();
    if (isSerializeNulls)
        builder.serializeNulls();
    if (version != null)
        builder.setVersion(version.doubleValue());
    if (StringUtils.isBlank(datePattern))
        datePattern = DEFAULT_DATE_PATTERN;
    builder.setDateFormat(datePattern);
    if (excludesFieldsWithoutExpose)
        builder.excludeFieldsWithoutExposeAnnotation();
    return toJson(target, targetType, builder);
}

From source file:cn.taop.utils.GSONUtils.java

License:Apache License

/**
 *  {@code JSON} ??/*  www  .j a  va 2s  .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 gson.fromJson(json, token.getType());
    } catch (Exception ex) {
        LOGGER.error(json + " ? " + token.getRawType().getName() + " !", ex);
        return null;
    }
}

From source file:cn.taop.utils.GSONUtils.java

License:Apache License

/**
 *  {@code JSON} ??<strong>?? {@code JavaBean} </strong>
 * //from  ww w  .  j  av a  2 s .  c om
 * @param <T> ??
 * @param json  {@code JSON} 
 * @param clazz ??
 * @param datePattern ??
 * @return  {@code JSON} 
 * @since 1.0
 */
public static <T> T fromJson(String json, Class<T> clazz, 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 gson.fromJson(json, clazz);
    } catch (Exception ex) {
        LOGGER.error(json + " ? " + clazz.getName() + " !", ex);
        return null;
    }
}

From source file:cn.teamlab.wg.framework.struts2.json.JsonSerializerBuilder.java

License:Apache License

public static GsonBuilder builder() {
    return new GsonBuilder() //
            .disableHtmlEscaping().registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
                @Override/*from   w  w  w .  j  a  va 2 s.  c om*/
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {
                    if (src == src.longValue())
                        return new JsonPrimitive(src.longValue());
                    return new JsonPrimitive(src);
                }
            }).registerTypeAdapter(Date.class, new DateTypeAdapter())
            .registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() {

                @Override
                public JsonElement serialize(DateTime arg0, Type arg1, JsonSerializationContext arg2) {
                    return new JsonPrimitive(arg0.toString(DateFormatter.SDF_YMDHMS6));
                }
            });
}

From source file:co.aikar.timings.TimingsExport.java

License:MIT License

@Override
public void run() {
    this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadStart"));
    this.out.add("data", JsonUtil.mapToArray(this.history, TimingsHistory::export));

    String response = null;/*w ww . jav a 2s .c  om*/
    try {
        HttpURLConnection con = (HttpURLConnection) new URL("http://timings.aikar.co/post").openConnection();
        con.setDoOutput(true);
        con.setRequestProperty("User-Agent",
                "Nukkit/" + Server.getInstance().getName() + "/" + InetAddress.getLocalHost().getHostName());
        con.setRequestMethod("POST");
        con.setInstanceFollowRedirects(false);

        OutputStream request = new GZIPOutputStream(con.getOutputStream()) {
            {
                this.def.setLevel(7);
            }
        };

        request.write(new Gson().toJson(this.out).getBytes("UTF-8"));
        request.close();

        response = getResponse(con);

        if (con.getResponseCode() != 302) {
            this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.uploadError",
                    new String[] { String.valueOf(con.getResponseCode()), con.getResponseMessage() }));
            if (response != null) {
                Server.getInstance().getLogger().alert(response);
            }
            return;
        }

        String location = con.getHeaderField("Location");
        this.sender.sendMessage(new TranslationContainer("nukkit.command.timings.timingsLocation", location));
        if (!(this.sender instanceof ConsoleCommandSender)) {
            Server.getInstance().getLogger().info(Server.getInstance().getLanguage()
                    .translateString("nukkit.command.timings.timingsLocation", location));
        }

        if (response != null && !response.isEmpty()) {
            Server.getInstance().getLogger().info(Server.getInstance().getLanguage()
                    .translateString("nukkit.command.timings.timingsResponse", response));
        }

        File timingFolder = new File(Server.getInstance().getDataPath() + File.separator + "timings");
        timingFolder.mkdirs();
        String fileName = timingFolder + File.separator
                + new SimpleDateFormat("'timings-'yyyy-MM-dd-hh-mm'.txt'").format(new Date());

        FileWriter writer = new FileWriter(fileName);
        writer.write(Server.getInstance().getLanguage()
                .translateString("nukkit.command.timings.timingsLocation", location) + "\n\n");
        writer.write(new GsonBuilder().setPrettyPrinting().create().toJson(this.out));
        writer.close();

        Server.getInstance().getLogger().info(Server.getInstance().getLanguage()
                .translateString("nukkit.command.timings.timingsWrite", fileName));
    } catch (IOException exception) {
        this.sender.sendMessage(
                TextFormat.RED + "" + new TranslationContainer("nukkit.command.timings.reportError"));
        if (response != null) {
            Server.getInstance().getLogger().alert(response);
        }
        Server.getInstance().getLogger().logException(exception);
    }
}

From source file:co.aurasphere.botmill.fb.internal.util.json.AttachmentDeserializer.java

License:Open Source License

/**
 * Instantiates a new AttachmentDeserializer.
 *//*w  ww  .  ja  va 2  s.  c  om*/
public AttachmentDeserializer() {
    GsonBuilder builder = new GsonBuilder();
    builder.addDeserializationExclusionStrategy(new SkipDeserializationAnnotationExclusionStrategy());
    delegateGson = builder.create();
}