List of usage examples for com.google.gson GsonBuilder create
public Gson create()
From source file:ca.jackymok.tomatoes.toolbox.GsonRequest.java
License:Apache License
public GsonRequest(int method, String url, Class<T> clazz, Listener<T> listener, ErrorListener errorListener) { super(Method.GET, url, errorListener); this.mClazz = clazz; this.mListener = listener; //Create Gson qith custom Date parsing GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() { final java.text.DateFormat df = new SimpleDateFormat("yyyy-MM-dd"); @Override/*from www.j a v a 2 s . c om*/ public Date deserialize(JsonElement arg0, java.lang.reflect.Type arg1, JsonDeserializationContext arg2) throws JsonParseException { try { return df.parse(arg0.getAsString()); } catch (final java.text.ParseException e) { e.printStackTrace(); return null; } } }); mGson = gsonBuilder.create(); }
From source file:ca.oson.json.Oson.java
License:Open Source License
public Gson getGson() { if (gson == null) { GsonBuilder gsonBuilder = new GsonBuilder(); switch (getDefaultType()) { case ALWAYS: gsonBuilder.serializeNulls(); break; case NON_NULL: break; case NON_EMPTY: break; case DEFAULT: gsonBuilder.serializeNulls(); break; default:/*from w w w. j a va 2s .c o m*/ gsonBuilder.serializeNulls(); break; } switch (getFieldNaming()) { case FIELD: // original field name: someField_name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY); break; case LOWER: // somefield_name -> some_field_name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); break; case UPPER: //SOMEFIELD_NAME -> SomeFieldName gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE); break; case CAMELCASE: // someFieldName gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY); break; case UPPER_CAMELCASE: // SomeFieldName gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE); break; case UNDERSCORE_CAMELCASE: // some_Field_Name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); break; case UNDERSCORE_UPPER_CAMELCASE: // Some_Field_Name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); break; case UNDERSCORE_LOWER: // some_field_name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); break; case UNDERSCORE_UPPER: // SOME_FIELD_NAME gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); break; case SPACE_CAMELCASE: // some Field Name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES); break; case SPACE_UPPER_CAMELCASE: // Some Field Name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES); break; case SPACE_LOWER: // some field name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES); break; case SPACE_UPPER: // SOME FIELD NAME gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE_WITH_SPACES); break; case DASH_CAMELCASE: // some-Field-Name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); break; case DASH_UPPER_CAMELCASE: // Some-Field-Name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); break; case DASH_LOWER: // some-field-name gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); break; case DASH_UPPER: // SOME-FIELD-NAME gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); break; default: gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.IDENTITY); break; } if (getPrettyPrinting() && getIndentation() > 0) { gsonBuilder.setPrettyPrinting(); } gsonBuilder.setDateFormat(options.getSimpleDateFormat()); Set<FieldMapper> mappers = getFieldMappers(); Map<Class, ClassMapper> classMappers = getClassMappers(); List<ExclusionStrategy> strategies = new ArrayList<>(); if (mappers != null) { gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() { @Override public String translateName(Field f) { String fieldName = f.getName(); String serializedName = java2Json(f); if (!fieldName.equalsIgnoreCase(serializedName)) { // if null returned, this field is ignored return serializedName; } return json2Java(f); } }); for (FieldMapper mapper : mappers) { if (mapper.java == null || mapper.json == null || mapper.ignore) { strategies.add(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { String name = f.getName(); Class cls = f.getClass(); if (mapper.java == null) { if (mapper.json.equals(name)) { if (mapper.getType() == null || cls.equals(mapper.getType())) { return true; } } } else if (mapper.json == null || mapper.ignore) { if (mapper.java.equals(name)) { if (mapper.getType() == null || cls.equals(mapper.getType())) { return true; } } } return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { return false; } }); } } } if (classMappers != null) { for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) { ClassMapper mapper = entry.getValue(); if (mapper.getType() == null) { mapper.setType(entry.getKey()); } if (mapper.ignore != null && mapper.ignore) { strategies.add(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes f) { return false; } @Override public boolean shouldSkipClass(Class<?> clazz) { if (clazz.equals(mapper.getType())) { return true; } return false; } }); } } for (Entry<Class, ClassMapper> entry : classMappers.entrySet()) { ClassMapper mapper = entry.getValue(); if (!mapper.ignore && mapper.constructor != null) { gsonBuilder.registerTypeAdapter(entry.getKey(), mapper.constructor); } } } int size = strategies.size(); if (size > 0) { gsonBuilder.setExclusionStrategies(strategies.toArray(new ExclusionStrategy[size])); } Double version = getVersion(); if (version != null) { gsonBuilder.setVersion(version); } if (isUseGsonExpose()) { gsonBuilder.excludeFieldsWithoutExposeAnnotation(); } if (!DefaultValue.isDefault(getPatterns())) { gsonBuilder.setLenient(); } gson = gsonBuilder.create(); } return gson; }
From source file:ca.ualberta.cmput301w14t08.geochan.helpers.GsonHelper.java
License:Apache License
private GsonHelper() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Comment.class, new CommentJsonConverter()); builder.registerTypeAdapter(ThreadComment.class, new ThreadCommentJsonConverter()); builder.registerTypeAdapter(Bitmap.class, new BitmapJsonConverter()); builder.registerTypeAdapter(Location.class, new LocationJsonConverter()); onlineGson = builder.create(); builder = new GsonBuilder(); builder.registerTypeAdapter(Comment.class, new CommentOfflineJsonConverter()); builder.registerTypeAdapter(ThreadComment.class, new ThreadCommentOfflineJsonConverter()); builder.registerTypeAdapter(Location.class, new LocationJsonConverter()); offlineGson = builder.create();//from ww w. j a v a2 s . c om builder = new GsonBuilder(); exposeGson = builder.excludeFieldsWithoutExposeAnnotation().create(); }
From source file:ca.ualberta.cs.c301f12t01.serverStorage.ReportServerRetrieval.java
License:Apache License
/** * Method works to get reports and tasks * //from ww w . j a v a 2 s. c om * @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./*from w w w . ja v a 2 s . c o m*/ * @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 w w . j av a 2s .co 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./* w ww.j a v a 2s .c o 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.legacy.GsonUtil.java
License:Open Source License
public static synchronized Gson getInstance() { if (gson == null) { final GsonBuilder builder = new GsonBuilder(); addTypeAdapters(builder);//from ww w . j av a2 s .c o m builder.enableComplexMapKeySerialization(); gson = builder.create(); } return gson; }
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 v a2 s . c o 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:cc.telepath.phage.PhageGroup.java
License:GNU General Public License
/** * Announce a new AES Key on all private channels. *//*from ww w.j av a2s . c o m*/ public void newEpochAnnouncement(String newKey, PhageFCPClient pcl) throws NoSuchPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, SignatureException, InvalidKeyException, IOException, FcpException, NoSuchProviderException { Crypto c = new Crypto(); Base64 base64 = new Base64(); GsonBuilder b = new GsonBuilder(); b.disableHtmlEscaping(); Gson g = b.create(); for (PhageIdentity pi : identityList) { EpochAnnouncement announcement = new EpochAnnouncement(newKey, identityList); String stringAnnouncement = g.toJson(announcement); String AESkey = c.generateAESKey(); byte[] encryptedAnnouncement = c.AESEncrypt(stringAnnouncement.getBytes(), AESkey); //EncrypotAndSign adds a colon to the string so we've been checking the wrong string //FIXME String encryptedKey = c.encryptAndSign(pi.getPubkey(), this.PrivateKey, AESkey); try { System.out.println( c.AESDecrypt(base64.decode(new String(base64.encode(encryptedAnnouncement))), AESkey)); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } System.out.println("Membership announcement on " + pcl.putData(privateChannels.get(pi.getFreenetPubkey()).replace("KSK@", ""), (encryptedKey + ":" + new String(base64.encode(encryptedAnnouncement))).getBytes(), null, null, "text/plain", false)); } }