Example usage for com.google.gson GsonBuilder registerTypeAdapter

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

Introduction

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

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public GsonBuilder registerTypeAdapter(Type type, Object typeAdapter) 

Source Link

Document

Configures Gson for custom serialization or deserialization.

Usage

From source file:com.datascience.gal.scripts.SerializationSanityChecks.java

License:Open Source License

/**
 * @param args//from w  w w. j  av a  2  s  .co  m
 */
public static void main(String[] args) {
    AssignedLabel al = new AssignedLabel("foo", "bar", "baz");
    System.out.println(al);
    String json = al.toString();
    GsonBuilder builder = new GsonBuilder();

    Type type = new TypeToken<AssignedLabel>() {
    }.getType();
    Type ctype = new TypeToken<CorrectLabel>() {
    }.getType();
    Type atype = new TypeToken<Collection<AssignedLabel>>() {
    }.getType();
    Type cattype = new TypeToken<Category>() {
    }.getType();
    Type catstype = new TypeToken<Collection<Category>>() {
    }.getType();
    Type mattype = new TypeToken<MultinomialConfusionMatrix>() {
    }.getType();

    builder.registerTypeAdapter(type, AssignedLabel.deserializer);
    builder.registerTypeAdapter(ctype, CorrectLabel.deserializer);
    builder.registerTypeAdapter(cattype, Category.deserializer);
    builder.registerTypeAdapter(mattype, MultinomialConfusionMatrix.deserializer);

    Gson gson = builder.create();
    System.out.println(gson.fromJson(json, type));
    System.out.println(gson.fromJson(json, type).getClass());
    CorrectLabel cl = new CorrectLabel("foo", "bar");
    System.out.println(cl);
    String t = cl.toString();
    System.out.println(gson.fromJson(t, ctype));
    System.out.println(gson.fromJson(t, ctype).getClass());

    Collection<AssignedLabel> col = new HashSet<AssignedLabel>();
    for (int i = 0; i < 10; i++) {
        String foo = i + "";
        col.add(new AssignedLabel(foo, foo, foo));
    }
    String tmp = gson.toJson(col);
    System.out.println(gson.fromJson(tmp, atype).getClass());

    Collection<Category> cats = new HashSet<Category>();
    for (int i = 0; i < 5; i++) {
        cats.add(new Category("" + i));
    }

    System.out.println(gson.toJson(cats));
    String foo = gson.toJson(cats);
    System.out.println(gson.fromJson(foo, catstype).getClass());

    Datum datum = new Datum("foo", new HashSet<Category>(cats));

    System.out.println(datum);

    Worker worker = new Worker("foo", new HashSet<Category>(cats));

    System.out.println(worker);

    ConfusionMatrix mat = new MultinomialConfusionMatrix(cats);
    String matrix = gson.toJson(mat);
    System.out.println(matrix);
    ConfusionMatrix mat2 = gson.fromJson(matrix, mattype);
    System.out.println(mat2.getClass());

}

From source file:com.datascience.serialization.json.JSONUtils.java

License:Open Source License

public static GsonBuilder getFilledDefaultGsonBuilder() {
    GsonBuilder builder = getDefaultGsonBuilder();
    builder.registerTypeAdapter(ConfusionMatrix.class,
            new MultinominalConfusionMatrixJSON.ConfusionMatrixDeserializer());
    builder.registerTypeAdapter(ConfusionMatrix.class,
            new MultinominalConfusionMatrixJSON.ConfusionMatrixSerializer());
    builder.registerTypeAdapter(InMemoryNominalData.class, new DataJSON.NominalDeserializer());
    builder.registerTypeAdapter(InMemoryNominalData.class, new DataJSON.NominalSerializer());
    builder.registerTypeAdapter(InMemoryData.class, new DataJSON.Serializer());
    builder.registerTypeAdapter(new TypeToken<InMemoryData<ContValue>>() {
    }.getType(), new DataJSON.ContValueDataDeserializer());
    builder.registerTypeAdapter(AssignedLabel.class, new DataJSON.AssignSerializer());
    builder.registerTypeAdapter(assignString,
            new DataJSON.AssignDeserializer<AssignedLabel<String>>(shallowAssignString));
    builder.registerTypeAdapter(assignContValue,
            new DataJSON.AssignDeserializer<AssignedLabel<ContValue>>(shallowAssignContValue));
    builder.registerTypeAdapter(Worker.class, new DataJSON.WorkerSerializer());
    builder.registerTypeAdapter(Worker.class, new DataJSON.WorkerDeserializer());
    builder.registerTypeAdapter(Serialized.class, new SerializedSerializer());
    builder.registerTypeAdapter(CostMatrix.class, new DataJSON.CostMatrixDeserializer<String>());
    builder.registerTypeAdapter(CostMatrix.class, new DataJSON.CostMatrixSerializer<String>());

    builder.registerTypeAdapter(ResultsFactory.DatumResultCreator.class,
            new DataJSON.DatumCreatorDeserializer());
    builder.registerTypeAdapter(ResultsFactory.WorkerResultCreator.class,
            new DataJSON.WorkerCreatorDeserializer());

    builder.registerTypeAdapter(JsonObject.class, new DataJSON.JsonObjectSerializer());
    builder.registerTypeAdapter(JsonObject.class, new DataJSON.JsonObjectDeserializer());

    builder.registerTypeAdapter(objectsStringType, new DataJSON.GenericCollectionDeserializer<LObject<String>>(
            "objects", new TypeToken<LObject<String>>() {
            }.getType()));/* ww  w. j  a  va2s  .com*/
    builder.registerTypeAdapter(objectsContValueType,
            new DataJSON.GenericCollectionDeserializer<LObject<ContValue>>("objects",
                    new TypeToken<LObject<ContValue>>() {
                    }.getType()));
    builder.registerTypeAdapter(shallowAssignsStringType,
            new DataJSON.GenericCollectionDeserializer<ShallowAssign<String>>("assigns", shallowAssignString));
    builder.registerTypeAdapter(shallowAssignsContValueType,
            new DataJSON.GenericCollectionDeserializer<ShallowAssign<ContValue>>("assigns",
                    shallowAssignContValue));

    return builder;
}

From source file:com.daxstudio.sa.base.model.provider.ProviderModule.java

License:Open Source License

@Singleton
@Provides/*w  ww. ja  v a  2  s .  c o  m*/
Gson provideGson(final GsonConfig config) {
    final GsonBuilder builder = new GsonBuilder();
    if (config.autoGsonTypeAdapterFactory() != null) {
        builder.registerTypeAdapterFactory(config.autoGsonTypeAdapterFactory());
    }
    return builder
            .registerTypeAdapter(ZonedDateTime.class,
                    new ZonedDateTimeJsonConverter(config.dateTimeFormatter()))
            .setDateFormat(config.dateFormatString()).setPrettyPrinting().create();
}

From source file:com.denimgroup.threadfix.importer.util.JsonUtils.java

License:Mozilla Public License

private static Gson getGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
    return gsonBuilder.create();
}

From source file:com.denimgroup.threadfix.remote.response.ResponseParser.java

License:Mozilla Public License

private static Gson getGson() {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Calendar.class, new CalendarSerializer());
    gsonBuilder.registerTypeAdapter(GregorianCalendar.class, new CalendarSerializer());
    gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer());
    gsonBuilder.registerTypeAdapter(byte[].class, new ByteToStringSerializer()); // needed for files.
    return gsonBuilder.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  ww  w. ja va  2 s .c  o m
        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;//from  ww  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();
        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  www  .ja  va 2 s  .  com*/
    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();/*w  w  w  .  ja  v  a 2s . c  o m*/
    IPoisClass result = (IPoisClass) gson.fromJson(data, IPoisClass.class);
    // String name = result.getClass().toString();
    return result;
}

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) {/*  w  ww . j  av  a2s.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();
}