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.devbliss.doctest.utils.JSONHelper.java

License:Apache License

/**
 * /*from   w w  w .  jav a  2s.com*/
 * Converts the given POJO and will skip the given fields while doing so.
 * If prettyPrint is true, the output will be nicely formatted.
 * 
 * @param obj
 * @param excludedFields
 * @param prettyPrint
 * @return
 */
public String toJsonAndSkipCertainFields(Object obj, final List<String> excludedFields, boolean prettyPrint) {
    ExclusionStrategy strategy = new ExclusionStrategy() {
        public boolean shouldSkipField(FieldAttributes f) {
            if (excludedFields.contains(f.getName())) {
                return true;
            }

            return false;
        }

        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    };

    GsonBuilder builder = new GsonBuilder().addSerializationExclusionStrategy(strategy)
            .addDeserializationExclusionStrategy(strategy);

    if (prettyPrint)
        builder.setPrettyPrinting();

    return builder.create().toJson(obj);
}

From source file:com.devbury.mkremote.api.GsonJsonService.java

License:Open Source License

public GsonJsonService() {
    GsonBuilder builder = new GsonBuilder();
    gson = builder.create();
}

From source file:com.devbury.mkremote.MkRemoteApplication.java

License:Open Source License

@Override
public void onCreate() {
    super.onCreate();
    Logger.init("mkRemote");
    handler = new EmailUncaughtExceptionHandler(this, Thread.getDefaultUncaughtExceptionHandler());
    Thread.setDefaultUncaughtExceptionHandler(handler);

    sdk = Integer.parseInt(Build.VERSION.SDK);
    Logger.debug("Android SDK " + sdk);

    try {//from   w  ww. j  a  v a 2s .com
        minServerVersion = getPackageManager().getApplicationInfo(getPackageName(),
                PackageManager.GET_META_DATA).metaData.getInt("MIN_SERVER_VERSION");
    } catch (NameNotFoundException e) {
    }
    MkRemotePreferences.setContext(this);
    MkRemotePreferences.initDefaults();

    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    SharedPreferencesPasswordStorageService pass = new SharedPreferencesPasswordStorageService();
    pass.setSharedPreferences(sharedPreferences);
    passwordStorageService = pass;

    GsonBuilder b = new GsonBuilder();
    b.registerTypeAdapter(MacroListResponsePacket.class, new MacroListResponsePacketDeserializer());
    b.registerTypeAdapter(QuickLaunchListResponsePacket.class, new QuickLaunchListResponsePacketDeserializer());
    jsonService = new GsonJsonService(b.create());
    ChainServerConnectionFactory chain = new ChainServerConnectionFactory();
    SocketServerConnectionFactory scf = new SocketServerConnectionFactory();
    scf.setJsonService(jsonService);
    chain.addServerConnectionFactory(scf);
    if (!isLite()) {
        NativeBluetoothServerConnectionFactory nf = new NativeBluetoothServerConnectionFactory();
        nf.setJsonService(jsonService);
        chain.addServerConnectionFactory(nf);
    }
    serverConnectionFactory = chain;
    serverConnectionFactory.init();

    MergeDiscoveryService mds = new MergeDiscoveryService();
    if (sdk == 3) {
        historyDiscoveryService = new HistoryDiscoveryService();
        historyDiscoveryService.setApp(this);
        historyDiscoveryService.setSharedPreferences(sharedPreferences);
        mds.addDiscoveryService(historyDiscoveryService);
    } else {
        MulticastDiscoveryService multi = new MulticastDiscoveryService();
        multi.setJsonService(jsonService);
        mds.addDiscoveryService(multi);
    }
    NativeBluetoothDiscoveryService native_service = new NativeBluetoothDiscoveryService();
    native_service.setSharedPreferences(sharedPreferences);
    native_service.setJsonService(jsonService);
    mds.addDiscoveryService(native_service);
    bluetoothType = BLUETOOTH_NATIVE;
    Logger.debug("Using native bluetooth");

    discoveryService = mds;

    try {
        MultiTouchHandler h = new MultiTouchHandler();
        multiTouchHandler = h;
        Logger.debug("Using multi-touch");
    } catch (Throwable t) {
        multiTouchHandler = new IMultiTouchHandler() {
            @Override
            public boolean processEvent(MotionEvent event) {
                return false;
            }
        };
        Logger.debug("No multi-touch");
    }

    if (sdk >= 5) {
        windowAttributeHelper = new Android20WindowAttributeHelper();
        Logger.debug("Android 2.0+ Window Helper");
    } else if (sdk == 4) {
        windowAttributeHelper = new Android16WindowAttributeHelper();
        Logger.debug("Android 1.6 Window Helper");
    } else {
        windowAttributeHelper = new Android15WindowAttributeHelper();
        Logger.debug("Android 1.5 Window Helper");
    }
}

From source file:com.dmsl.anyplace.nav.AnyPlaceSeachingHelper.java

License:Open Source License

public static Cursor prepareSearchViewCursor(List<? extends IPoisClass> places) {
    String req_columns[] = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_TEXT_2, SearchManager.SUGGEST_COLUMN_INTENT_DATA };
    MatrixCursor mcursor = new MatrixCursor(req_columns);
    int i = 0;/*w w  w .  j  a va 2s .c o m*/
    if (places != null) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(IPoisClass.class, new IPoisClass.MyInterfaceAdapter());
        Gson gson = gsonBuilder.create();
        for (IPoisClass p : places) {
            mcursor.addRow(new String[] { Integer.toString(i++), p.name(),
                    p.description().equals("") ? "no description" : p.description(),
                    gson.toJson(p, IPoisClass.class) });
        }
    }
    return mcursor;
}

From source file:com.dmsl.anyplace.nav.AnyPlaceSeachingHelper.java

License:Open Source License

public static Cursor prepareSearchViewCursor(List<? extends IPoisClass> places, String query) {
    String req_columns[] = { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1,
            SearchManager.SUGGEST_COLUMN_INTENT_DATA };
    MatrixCursor mcursor = new MatrixCursor(req_columns);
    int i = 0;/*from   w w w. j  av a 2s.  co  m*/
    if (places != null) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(IPoisClass.class, new IPoisClass.MyInterfaceAdapter());
        Gson gson = gsonBuilder.create();

        // Better Use AndroidUtils.fillTextBox instead of regular expression
        // Regular expression
        // ?i ignore case
        Pattern patternTitle = Pattern.compile(String.format("((?i)%s)", query));
        // Matches X words before query and Y words after
        Pattern patternDescription = Pattern.compile(
                String.format("(([^\\s]+\\s+){0,%d}[^\\s]*)((?i)%s)([^\\s]*(\\s+[^\\s]+){0,%d})", 2, query, 2));
        for (IPoisClass p : places) {
            String name = "", description = "";
            Matcher m;
            m = patternTitle.matcher(p.name());
            // Makes matched query bold using HTML format
            // $1 returns the regular's expression outer parenthesis value
            name = m.replaceAll("<b>$1</b>");

            m = patternDescription.matcher(p.description());
            if (m.find()) {
                // Makes matched query bold using HTML format
                description = String.format(" %s<b>%s</b>%s", m.group(1), m.group(3), m.group(4));
            }

            mcursor.addRow(new String[] { Integer.toString(i++), name + description,
                    gson.toJson(p, IPoisClass.class) });
        }
    }
    return mcursor;
}

From source file:com.dmsl.anyplace.nav.AnyPlaceSeachingHelper.java

License:Open Source License

public static IPoisClass getClassfromJson(String data) {
    // HANDLE BOTH GooglePlace AND AnyplacePoi
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(IPoisClass.class, new IPoisClass.MyInterfaceAdapter());
    Gson gson = gsonBuilder.create();
    IPoisClass result = (IPoisClass) gson.fromJson(data, IPoisClass.class);
    // String name = result.getClass().toString();
    return result;
}

From source file:com.dragonwellstudios.mahjonghandhelper.riichi.fragments.YakuFragment.java

License:Open Source License

@Override
public void onStart() {
    super.onStart();
    GsonBuilder builder = new GsonBuilder();
    Gson gson = builder.create();

    yaku = gson.fromJson(new InputStreamReader(getResources().openRawResource(R.raw.yaku)), Yaku[].class);
    for (Yaku y : yaku) {
        int resId = getResources().getIdentifier(y.getName(), "string",
                MainActivity.class.getPackage().getName());
        if (resId != 0) {
            y.setName(getString(resId));
        }/*from   w w w.  j a v a 2 s  .c o  m*/
    }

    yakuList.setLayoutManager(new LinearLayoutManager(getActivity()));
    yakuList.setAdapter(new YakuListAdapter(yaku));
}

From source file:com.drguildo.bm.BookmarksManager.java

License:Open Source License

public static void save(Bookmarks bookmarks) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
    gsonBuilder.registerTypeAdapter(Tags.class, new TagsSerializer());

    if (DEBUG) {/*from   ww w. jav a 2 s .c o m*/
        Gson gson = gsonBuilder.setPrettyPrinting().create();
        System.out.println(gson.toJson(bookmarks.toArrayList()));
        return;
    }

    if (bookmarkFile.exists()) {
        Files.move(bookmarkFile.toPath(), new File(bookmarkFile.getPath() + ".bak").toPath(),
                StandardCopyOption.REPLACE_EXISTING);
    } else {
        if (!bookmarkFile.createNewFile()) {
            throw new IOException("Failed to create bookmark file.");
        }
    }

    FileWriter writer = new FileWriter(bookmarkFile);
    writer.write(gsonBuilder.create().toJson(bookmarks.toArrayList()));
    writer.flush();
    writer.close();
}

From source file:com.droiddevil.myuber.data.DataModule.java

License:Apache License

@Provides
@Singleton/*from   w  w  w . jav a2  s.com*/
Gson provideGson() {
    GsonBuilder builder = new GsonBuilder();

    if (BuildConfig.DEBUG) {
        builder.setPrettyPrinting();
    }

    return builder.create();

}

From source file:com.eclipsesource.connect.serialization.GsonFactory.java

License:Open Source License

public static Gson create(boolean prettyPrinting) {
    GsonBuilder builder = new GsonBuilder();
    if (prettyPrinting) {
        builder.setPrettyPrinting();//from w w  w  . j av a  2s  .co  m
    }
    builder.registerTypeAdapter(Id.class, new IdTypeAdapter());
    Converters.registerAll(builder);
    addFieldNamingStrategy(builder);
    return builder.create();
}