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:ca.ualberta.cs.c301f12t01.serverStorage.ReportServerRetrieval.java

License:Apache License

/**
 * Method works to get reports and tasks
 * /*from w w  w .j ava  2 s .c o  m*/
 * @param id
 *            Server ID of the content we want to get
 * @return content from server
 */
public static Report getContentFromServer(String id) {
    // create our nvp
    List<BasicNameValuePair> nvp = new ArrayList<BasicNameValuePair>();
    nvp.add(new BasicNameValuePair("action", "get"));
    nvp.add(new BasicNameValuePair("id", id));
    // post
    Server server = new Server();
    String jsonString = server.post(nvp);

    // convert to SO
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Response.class, new ResponseDeserializer());
    Gson gson = gsonBuilder.create();

    ReportServerObj so = gson.fromJson(jsonString, ReportServerObj.class);
    return so.getContent();
}

From source file:ca.ualberta.cs.scandaloutraveltracker.mappers.UserMapper.java

License:Apache License

/**
 * Saves the user data, one field at a time. The field it saves
 * is associated with the key./*  www  . j  ava 2s  .c  om*/
 * @param userId
 * @param key
 * @param data
 */
public void saveUserData(int userId, String key, Object data) {

    SharedPreferences userFile = this.context.getSharedPreferences(getUserFileName(userId), 0);
    Editor editor = userFile.edit();
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Location.class, new LocationDeserializer());
    gsonBuilder.registerTypeAdapter(Location.class, new LocationSerializer());
    Gson gson = gsonBuilder.create();

    if (key.equals("id")) {
        editor.putInt("id", (Integer) data);
    } else if (key.equals("name")) {
        editor.putString(key, (String) data);
    } else if (key.equals("location")) {
        String locationsJson = gson.toJson((Location) data);
        editor.putString(key, locationsJson);
    }

    editor.commit();
}

From source file:ca.ualberta.cs.scandaloutraveltracker.mappers.UserMapper.java

License:Apache License

/**
 * Loads user data one field at a time. The field loaded is associated
 * with the key./*from  w ww  . j a  v  a 2s  .c  o m*/
 * @param userId
 * @param key
 * @return User associated with userId
 */
public Object loadUserData(int userId, String key) {

    Object data = 0;
    SharedPreferences userFile = this.context.getSharedPreferences(getUserFileName(userId), 0);
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Location.class, new LocationDeserializer());
    gsonBuilder.registerTypeAdapter(Location.class, new LocationSerializer());
    Gson gson = gsonBuilder.create();

    if (key.equals("id")) {
        data = userFile.getInt(key, -1);
    } else if (key.equals("name")) {
        data = userFile.getString(key, "");
    } else if (key.equals("location")) {
        String locationsJson = userFile.getString(key, "");
        Type type = new TypeToken<Location>() {
        }.getType();
        data = gson.fromJson(locationsJson, type);
    }

    return data;
}

From source file:ca.udes.android_projectweather.network.ForecastClient.java

License:Apache License

/**
 * Configure the gson./*  ww  w.  jav a 2  s  . co  m*/
 *
 * @return       builder.create()
 */
private static Gson createGson() {
    final long MILLIS = 1000;
    GsonBuilder builder = new GsonBuilder();

    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                throws JsonParseException {
            return new Date(json.getAsJsonPrimitive().getAsLong() * MILLIS);
        }
    });
    return builder.create();
}

From source file:cc.kave.commons.utils.json.JsonUtils.java

License:Apache License

private static GsonBuilder createBuilder() {
    GsonBuilder gb = new GsonBuilder();

    // add support for new Java 8 date/time framework
    gb.registerTypeHierarchyAdapter(LocalDateTime.class, new LocalDateTimeConverter());
    Converters.registerAll(gb);//from w ww .  jav a 2 s  . c om
    gb.registerTypeAdapter(Duration.class, new DurationConverter());

    GsonUtil.addTypeAdapters(gb);

    registerNames(gb);
    registerSSTHierarchy(gb);
    registerEventHierarchy(gb);

    gb.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE);
    gb.excludeFieldsWithModifiers(java.lang.reflect.Modifier.TRANSIENT);

    return gb;
}

From source file:cc.kave.commons.utils.json.JsonUtils.java

License:Apache License

private static void registerNames(GsonBuilder gb) {

    Class<?>[] names = new Class<?>[] {
            /* ----- v0 ----- */
            GeneralName.class,
            // code elements
            AliasName.class, EventName.class, FieldName.class, LambdaName.class, LocalVariableName.class,
            MethodName.class, ParameterName.class, PropertyName.class,
            // ide components
            CommandBarControlName.class, CommandName.class, DocumentName.class, ProjectItemName.class,
            ProjectName.class, SolutionName.class, WindowName.class,
            // others
            ReSharperLiveTemplateName.class,
            // types
            AssemblyName.class, AssemblyVersion.class, NamespaceName.class,
            ////w  w w  .j  a  va 2  s .c o  m
            ArrayTypeName.class, DelegateTypeName.class, PredefinedTypeName.class, TypeName.class,
            TypeParameterName.class
            /* ----- v1 ----- */
            // yet to come...
    };

    GsonNameDeserializer nameAdapter = new GsonNameDeserializer();

    Set<Class<?>> allNamesInHierarchy = Sets.newHashSet();

    for (Class<?> concreteName : names) {
        for (Class<?> nameType : getAllTypesFromHierarchyExceptObject(concreteName, true)) {
            allNamesInHierarchy.add(nameType);
        }
    }

    for (Class<?> name : allNamesInHierarchy) {
        gb.registerTypeAdapter(name, nameAdapter);
    }
}

From source file:cc.kave.commons.utils.json.JsonUtils.java

License:Apache License

private static <T extends Enum<T>> void registerEnum(GsonBuilder gb, Class<T> e) {
    T[] constants = e.getEnumConstants();
    gb.registerTypeAdapter(e, EnumDeSerializer.create(constants));
}

From source file:cc.kave.commons.utils.json.legacy.GsonUtil.java

License:Open Source License

public static void addTypeAdapters(final GsonBuilder builder) {
    builder.registerTypeAdapter(CoReMethodName.class, new GsonNameSerializer());
    builder.registerTypeAdapter(ICoReMethodName.class, new GsonNameSerializer());
    builder.registerTypeAdapter(CoReMethodName.class, new GsonMethodNameDeserializer());
    builder.registerTypeAdapter(ICoReMethodName.class, new GsonMethodNameDeserializer());
    builder.registerTypeAdapter(CoReTypeName.class, new GsonNameSerializer());
    builder.registerTypeAdapter(ICoReTypeName.class, new GsonNameSerializer());
    builder.registerTypeAdapter(CoReTypeName.class, new GsonTypeNameDeserializer());
    builder.registerTypeAdapter(ICoReTypeName.class, new GsonTypeNameDeserializer());
    builder.registerTypeAdapter(CoReFieldName.class, new GsonNameSerializer());
    builder.registerTypeAdapter(ICoReFieldName.class, new GsonNameSerializer());
    builder.registerTypeAdapter(CoReFieldName.class, new GsonFieldNameDeserializer());
    builder.registerTypeAdapter(ICoReFieldName.class, new GsonFieldNameDeserializer());
    ///*from w w  w .  jav a2s  . co m*/
    builder.registerTypeAdapter(File.class, new GsonFileDeserializer());
    builder.registerTypeAdapter(File.class, new GsonFileSerializer());
    // builder.setPrettyPrinting();
    // builder.setDateFormat("dd.MM.yyyy HH:mm:ss");
    builder.registerTypeAdapter(Date.class, new ISO8601DateParser());

    builder.registerTypeAdapter(Multimap.class, new MultimapTypeAdapter());
    //
    builder.registerTypeAdapter(Usage.class, new UsageTypeAdapter());
    builder.registerTypeAdapter(Query.class, new UsageTypeAdapter());
    builder.registerTypeAdapter(NoUsage.class, new UsageTypeAdapter());

    RuntimeTypeAdapterFactory<UsageFeature> rtaf = RuntimeTypeAdapterFactory.of(UsageFeature.class, "$type")
            .registerSubtype(CallFeature.class).registerSubtype(ClassFeature.class)
            .registerSubtype(DefinitionFeature.class).registerSubtype(FirstMethodFeature.class)
            .registerSubtype(ParameterFeature.class).registerSubtype(SuperMethodFeature.class)
            .registerSubtype(TypeFeature.class);
    builder.registerTypeAdapterFactory(rtaf);

    builder.registerTypeAdapter(CallFeature.class, new ObjectUsageFeatureRedirector<CallFeature>());
    builder.registerTypeAdapter(ClassFeature.class, new ObjectUsageFeatureRedirector<ClassFeature>());
    builder.registerTypeAdapter(DefinitionFeature.class, new ObjectUsageFeatureRedirector<DefinitionFeature>());
    builder.registerTypeAdapter(FirstMethodFeature.class,
            new ObjectUsageFeatureRedirector<FirstMethodFeature>());
    builder.registerTypeAdapter(ParameterFeature.class, new ObjectUsageFeatureRedirector<ParameterFeature>());
    builder.registerTypeAdapter(SuperMethodFeature.class,
            new ObjectUsageFeatureRedirector<SuperMethodFeature>());
    builder.registerTypeAdapter(TypeFeature.class, new ObjectUsageFeatureRedirector<TypeFeature>());
}

From source file:cc.recommenders.utils.gson.GsonUtil.java

License:Open Source License

public static synchronized Gson getInstance() {
    if (gson == null) {
        final GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(VmMethodName.class, new GsonNameSerializer());
        builder.registerTypeAdapter(IMethodName.class, new GsonNameSerializer());
        builder.registerTypeAdapter(VmMethodName.class, new GsonMethodNameDeserializer());
        builder.registerTypeAdapter(IMethodName.class, new GsonMethodNameDeserializer());
        builder.registerTypeAdapter(VmTypeName.class, new GsonNameSerializer());
        builder.registerTypeAdapter(ITypeName.class, new GsonNameSerializer());
        builder.registerTypeAdapter(VmTypeName.class, new GsonTypeNameDeserializer());
        builder.registerTypeAdapter(ITypeName.class, new GsonTypeNameDeserializer());
        builder.registerTypeAdapter(VmFieldName.class, new GsonNameSerializer());
        builder.registerTypeAdapter(IFieldName.class, new GsonNameSerializer());
        builder.registerTypeAdapter(VmFieldName.class, new GsonFieldNameDeserializer());
        builder.registerTypeAdapter(IFieldName.class, new GsonFieldNameDeserializer());
        ///*w  w w.  ja  va2  s. co m*/
        builder.registerTypeAdapter(File.class, new GsonFileDeserializer());
        builder.registerTypeAdapter(File.class, new GsonFileSerializer());
        // builder.setPrettyPrinting();
        // builder.setDateFormat("dd.MM.yyyy HH:mm:ss");
        builder.registerTypeAdapter(Date.class, new ISO8601DateParser());
        builder.registerTypeAdapter(Multimap.class, new MultimapTypeAdapter());
        //
        builder.registerTypeAdapter(Usage.class, new UsageTypeAdapter());
        builder.registerTypeAdapter(Query.class, new UsageTypeAdapter());

        RuntimeTypeAdapterFactory<UsageFeature> rtaf = RuntimeTypeAdapterFactory.of(UsageFeature.class, "$type")
                .registerSubtype(CallFeature.class).registerSubtype(ClassFeature.class)
                .registerSubtype(DefinitionFeature.class).registerSubtype(FirstMethodFeature.class)
                .registerSubtype(ParameterFeature.class).registerSubtype(SuperMethodFeature.class)
                .registerSubtype(TypeFeature.class);
        builder.registerTypeAdapterFactory(rtaf);

        builder.registerTypeAdapter(CallFeature.class, new ObjectUsageFeatureRedirector<CallFeature>());
        builder.registerTypeAdapter(ClassFeature.class, new ObjectUsageFeatureRedirector<ClassFeature>());
        builder.registerTypeAdapter(DefinitionFeature.class,
                new ObjectUsageFeatureRedirector<DefinitionFeature>());
        builder.registerTypeAdapter(FirstMethodFeature.class,
                new ObjectUsageFeatureRedirector<FirstMethodFeature>());
        builder.registerTypeAdapter(ParameterFeature.class,
                new ObjectUsageFeatureRedirector<ParameterFeature>());
        builder.registerTypeAdapter(SuperMethodFeature.class,
                new ObjectUsageFeatureRedirector<SuperMethodFeature>());
        builder.registerTypeAdapter(TypeFeature.class, new ObjectUsageFeatureRedirector<TypeFeature>());

        builder.enableComplexMapKeySerialization();
        gson = builder.create();
    }
    return gson;
}

From source file:cd.education.data.collector.android.tasks.GoogleMapsEngineAbstractUploader.java

License:Apache License

private String buildJSONSubmission(HashMap<String, String> answersToUpload,
        HashMap<String, PhotoEntry> uploadedPhotos) throws GeoPointNotFoundException {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Feature.class, new FeatureSerializer());
    gsonBuilder.registerTypeAdapter(ArrayList.class, new FeatureListSerializer());
    final Gson gson = gsonBuilder.create();

    Map<String, String> properties = new HashMap<String, String>();
    properties.put("gx_id", String.valueOf(System.currentTimeMillis()));

    // there has to be a geo point, else we can't upload
    boolean foundGeo = false;
    PointGeometry pg = null;//www .jav  a 2 s.  com

    Iterator<String> answerIterator = answersToUpload.keySet().iterator();
    while (answerIterator.hasNext()) {
        String path = answerIterator.next();
        String answer = answersToUpload.get(path);

        // the instances don't have data types, so we try to match a
        // fairly specific pattern to determine geo coordinates, so we
        // pattern match against our answer
        // [-]#.# [-]#.# #.# #.#
        if (!foundGeo) {
            Pattern p = Pattern
                    .compile("^-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s-?[0-9]+\\.[0-9]+\\s[0-9]+\\.[0-9]+$");
            Matcher m = p.matcher(answer);
            if (m.matches()) {
                foundGeo = true;
                // split on spaces, take the first two, which are lat
                // long
                String[] tokens = answer.split(" ");
                pg = new PointGeometry();
                pg.type = "Point";
                pg.setCoordinates(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[0]));
            }
        }

        // geo or not, add to properties
        properties.put(path, answer);
    }

    if (!foundGeo) {
        throw new GeoPointNotFoundException("Instance has no Coordinates! Unable to upload");
    }

    // then add the urls for photos
    Iterator<String> photoIterator = uploadedPhotos.keySet().iterator();
    while (photoIterator.hasNext()) {
        String path = photoIterator.next();
        String url = uploadedPhotos.get(path).getImageLink();
        properties.put(path, url);
    }

    Feature f = new Feature();
    f.geometry = pg;
    f.properties = properties;

    // gme expects an array of features for uploads, even though we only
    // send one
    ArrayList<Feature> features = new ArrayList<Feature>();
    features.add(f);

    return gson.toJson(features);
}