com.google.gson.FieldNamingPolicy Java Examples

The following examples show how to use com.google.gson.FieldNamingPolicy. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GaePendingResult.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
/**
 * @param request HTTP request to execute.
 * @param client The client used to execute the request.
 * @param responseClass Model class to unmarshal JSON body content.
 * @param fieldNamingPolicy FieldNamingPolicy for unmarshaling JSON.
 * @param errorTimeOut Number of milliseconds to re-send erroring requests.
 * @param maxRetries Number of times allowed to re-send erroring requests.
 */
public GaePendingResult(
    HTTPRequest request,
    URLFetchService client,
    Class<R> responseClass,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeOut,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry,
    RequestMetrics metrics) {
  this.request = request;
  this.client = client;
  this.responseClass = responseClass;
  this.fieldNamingPolicy = fieldNamingPolicy;
  this.errorTimeOut = errorTimeOut;
  this.maxRetries = maxRetries;
  this.exceptionsAllowedToRetry = exceptionsAllowedToRetry;
  this.metrics = metrics;

  metrics.startNetwork();
  this.call = client.fetchAsync(request);
}
 
Example #2
Source File: ResolveNuance.java    From Saiy-PS with GNU Affero General Public License v3.0 6 votes vote down vote up
public void unpack(@NonNull final JSONObject payload) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "unpacking");
    }

    final GsonBuilder builder = new GsonBuilder();
    builder.disableHtmlEscaping();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);

    final Gson gson = builder.create();
    nluNuance = gson.fromJson(payload.toString(), new TypeToken<NLUNuance>() {
    }.getType());

    new NLUCoerce(getNLUNuance(), getContext(), getSupportedLanguage(), getVRLocale(), getTTSLocale(),
            getConfidenceArray(), getResultsArray()).coerce();
}
 
Example #3
Source File: ResolveSaiy.java    From Saiy-PS with GNU Affero General Public License v3.0 6 votes vote down vote up
public void unpack(@NonNull final JSONObject payload) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "unpacking");
    }

    final GsonBuilder builder = new GsonBuilder();
    builder.disableHtmlEscaping();
    builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);

    final Gson gson = builder.create();
    nluSaiy = gson.fromJson(payload.toString(), new TypeToken<NLUSaiy>() {
    }.getType());

    new NLUCoerce(getNLUSaiy(), getContext(), getSupportedLanguage(), getVRLocale(), getTTSLocale(),
            getConfidenceArray(), getResultsArray()).coerce();
}
 
Example #4
Source File: HttpZallyService.java    From intellij-swagger with MIT License 6 votes vote down vote up
private static ZallyApi connect() {
  final String zallyUrl = ServiceManager.getService(ZallySettings.class).getZallyUrl();

  if (zallyUrl == null || zallyUrl.isEmpty()) {
    throw new RuntimeException("Zally URL is missing");
  }

  final Gson gson =
      new GsonBuilder()
          .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
          .create();
  final Decoder decoder = new GsonDecoder(gson);

  return Feign.builder()
      .encoder(new GsonEncoder())
      .decoder(decoder)
      .errorDecoder(new LintingResponseErrorDecoder())
      .logger(new Logger.ErrorLogger())
      .logLevel(Logger.Level.BASIC)
      .target(ZallyApi.class, zallyUrl);
}
 
Example #5
Source File: OkHttpPendingResult.java    From google-maps-services-java with Apache License 2.0 6 votes vote down vote up
/**
 * @param request HTTP request to execute.
 * @param client The client used to execute the request.
 * @param responseClass Model class to unmarshal JSON body content.
 * @param fieldNamingPolicy FieldNamingPolicy for unmarshaling JSON.
 * @param errorTimeOut Number of milliseconds to re-send erroring requests.
 * @param maxRetries Number of times allowed to re-send erroring requests.
 * @param exceptionsAllowedToRetry The exceptions to retry.
 */
public OkHttpPendingResult(
    Request request,
    OkHttpClient client,
    Class<R> responseClass,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeOut,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry,
    RequestMetrics metrics) {
  this.request = request;
  this.client = client;
  this.responseClass = responseClass;
  this.fieldNamingPolicy = fieldNamingPolicy;
  this.errorTimeOut = errorTimeOut;
  this.maxRetries = maxRetries;
  this.exceptionsAllowedToRetry = exceptionsAllowedToRetry;
  this.metrics = metrics;

  metrics.startNetwork();
  this.call = client.newCall(request);
}
 
Example #6
Source File: ArmeriaRequestHandler.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handlePost(
    String hostName,
    String url,
    String payload,
    String userAgent,
    String experienceIdHeaderValue,
    Class<R> clazz,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeout,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry,
    RequestMetrics metrics) {
  return handleMethod(
      HttpMethod.POST,
      hostName,
      url,
      HttpData.ofUtf8(payload),
      userAgent,
      experienceIdHeaderValue,
      clazz,
      fieldNamingPolicy,
      errorTimeout,
      maxRetries,
      exceptionsAllowedToRetry);
}
 
Example #7
Source File: ArmeriaRequestHandler.java    From curiostack with MIT License 6 votes vote down vote up
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handle(
    String hostName,
    String url,
    String userAgent,
    String experienceIdHeaderValue,
    Class<R> clazz,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeout,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry,
    RequestMetrics metrics) {
  return handleMethod(
      HttpMethod.GET,
      hostName,
      url,
      HttpData.empty(),
      userAgent,
      experienceIdHeaderValue,
      clazz,
      fieldNamingPolicy,
      errorTimeout,
      maxRetries,
      exceptionsAllowedToRetry);
}
 
Example #8
Source File: ArmeriaRequestHandler.java    From curiostack with MIT License 6 votes vote down vote up
private static Gson gsonForPolicy(FieldNamingPolicy fieldNamingPolicy) {
  return GSONS.computeIfAbsent(
      fieldNamingPolicy,
      policy ->
          new GsonBuilder()
              .registerTypeAdapter(ZonedDateTime.class, new ZonedDateTimeAdapter())
              .registerTypeAdapter(Distance.class, new DistanceAdapter())
              .registerTypeAdapter(Duration.class, new DurationAdapter())
              .registerTypeAdapter(Fare.class, new FareAdapter())
              .registerTypeAdapter(LatLng.class, new LatLngAdapter())
              .registerTypeAdapter(
                  AddressComponentType.class, new SafeEnumAdapter<>(AddressComponentType.UNKNOWN))
              .registerTypeAdapter(AddressType.class, new SafeEnumAdapter<>(AddressType.UNKNOWN))
              .registerTypeAdapter(TravelMode.class, new SafeEnumAdapter<>(TravelMode.UNKNOWN))
              .registerTypeAdapter(
                  LocationType.class, new SafeEnumAdapter<>(LocationType.UNKNOWN))
              .registerTypeAdapter(RatingType.class, new SafeEnumAdapter<>(RatingType.UNKNOWN))
              .registerTypeAdapter(DayOfWeek.class, new DayOfWeekAdapter())
              .registerTypeAdapter(PriceLevel.class, new PriceLevelAdapter())
              .registerTypeAdapter(Instant.class, new InstantAdapter())
              .registerTypeAdapter(LocalTime.class, new LocalTimeAdapter())
              .registerTypeAdapter(
                  GeolocationApi.Response.class, new GeolocationResponseAdapter())
              .setFieldNamingPolicy(policy)
              .create());
}
 
Example #9
Source File: GoogleTaskApi.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 6 votes vote down vote up
@Override
public T deserialize(JsonElement je, Type type,
		JsonDeserializationContext jdc) throws JsonParseException {
	// Get the "content" element from the parsed JSON
       JsonElement items = je.getAsJsonObject().get("items");

    Gson gson = new GsonBuilder()
	.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
       .registerTypeAdapter(Task.class, new TaskTypeAdapter())
       .create();

       // Deserialize it. You use a new instance of Gson to avoid infinite recursion
       // to this deserializer
       return gson.fromJson(items, type);	
       
}
 
Example #10
Source File: NatRuleTest.java    From cosmic with Apache License 2.0 6 votes vote down vote up
@Test
public void testNatRuleEncoding() {
    final Gson gson =
            new GsonBuilder().registerTypeAdapter(NatRule.class, new NatRuleAdapter())
                             .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                             .create();

    final DestinationNatRule rn1 = new DestinationNatRule();
    rn1.setToDestinationIpAddress("10.10.10.10");
    rn1.setToDestinationPort(80);
    final Match mr1 = new Match();
    mr1.setSourceIpAddresses("11.11.11.11/24");
    mr1.setEthertype("IPv4");
    mr1.setProtocol(6);
    rn1.setMatch(mr1);

    final String jsonString = gson.toJson(rn1);
    final NatRule dnr = gson.fromJson(jsonString, NatRule.class);

    assertTrue(dnr instanceof DestinationNatRule);
    assertTrue(rn1.equals(dnr));
}
 
Example #11
Source File: Attributes.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * Generate an output file containing all Person attributes used in Synthea.
 * Attributes of Clinicians and Providers are not included.
 * 
 * @param args unused
 * @throws Exception if any error occurs in reading the module files
 */
public static void main(String[] args) throws Exception {
  System.out.println("Performing an inventory of attributes into `output/attributes.json`...");
  
  Map<String,Inventory> output = getAttributeInventory();
  
  String outFilePath = new File("./output/attributes.json").toPath().toString();
  Writer writer = new FileWriter(outFilePath);
  Gson gson = new GsonBuilder()
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      .setPrettyPrinting().create();
  gson.toJson(output, writer);
  writer.flush();
  writer.close();
  
  graph(output, "attributes_all", false);
  graph(output, "attributes_readwrite", true);
  
  System.out.println("Catalogued " + output.size() + " attributes.");
  System.out.println("Done.");
}
 
Example #12
Source File: TMDbClient.java    From Amphitheatre with Apache License 2.0 6 votes vote down vote up
private static TMDbService getService() {
    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

    if (service == null) {
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setConverter(new GsonConverter(gson))
                .setEndpoint(ApiConstants.TMDB_SERVER_URL)
                .setRequestInterceptor(new RequestInterceptor() {
                    @Override
                    public void intercept(RequestFacade request) {
                        request.addQueryParam("api_key", ApiConstants.TMDB_SERVER_API_KEY);
                    }
                })
                .build();
        service = restAdapter.create(TMDbService.class);
    }
    return service;
}
 
Example #13
Source File: ScanUtil.java    From fluo with Apache License 2.0 6 votes vote down vote up
/**
 * Generate JSON format as result of the scan.
 *
 * @since 1.2
 */
private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,
    PrintStream out) throws JsonIOException {
  Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)
      .create();

  Map<String, String> json = new LinkedHashMap<>();
  for (RowColumnValue rcv : cellScanner) {
    json.put(FLUO_ROW, encoder.apply(rcv.getRow()));
    json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));
    json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));
    json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));
    json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));
    gson.toJson(json, out);
    out.append("\n");

    if (out.checkError()) {
      break;
    }
  }
  out.flush();
}
 
Example #14
Source File: GhostApiUtils.java    From quill with MIT License 6 votes vote down vote up
public static Retrofit getRetrofit(@NonNull String blogUrl, @NonNull OkHttpClient httpClient) {
    String baseUrl = NetworkUtils.makeAbsoluteUrl(blogUrl, "ghost/api/v0.1/");
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateDeserializer())
            .registerTypeAdapter(ConfigurationList.class, new ConfigurationListDeserializer())
            .registerTypeAdapterFactory(new PostTypeAdapterFactory())
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setExclusionStrategies(new RealmExclusionStrategy(), new AnnotationExclusionStrategy())
            .create();
    return new Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(httpClient)
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            // for HTML output (e.g., to get the client secret)
            .addConverterFactory(StringConverterFactory.create())
            // for raw JSONObject output (e.g., for the /configuration/about call)
            .addConverterFactory(JSONObjectConverterFactory.create())
            // for domain objects
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
}
 
Example #15
Source File: JSONTests.java    From sana.mobile with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void testLocation() {
    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .create();
    Type type = new TypeToken<Response<Collection<Location>>>() {
    }.getType();

    Collection<Location> objs = Collections.EMPTY_LIST;
    try {
        Response<Collection<Location>> response = gson.fromJson(locationJSON, type);
        objs = response.message;
    } catch (Exception e) {

    }
    assertTrue(objs.size() == 15);
}
 
Example #16
Source File: Model.java    From udacity-p1-p2-popular-movies with MIT License 6 votes vote down vote up
public Model() {
    mDatabase = new Database();
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(Date.class, new DateDeserializer())
            .registerTypeAdapter(new TypeToken<RealmList<Video>>() {}.getType(), new VideoRealmListDeserializer())
            .registerTypeAdapter(new TypeToken<RealmList<Review>>() {}.getType(), new ReviewRealmListDeserializer())
            .setExclusionStrategies(new RealmExclusionStrategy())
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();
    mApiService = retrofit.create(MovieDBApiService.class);
    mApiKey = "075c3ac2845f0a71e38797ec6f57cdfb";
    getDataBus().register(this);
}
 
Example #17
Source File: DebugApiServiceModule.java    From android-test-demo with MIT License 6 votes vote down vote up
@Provides @Singleton
public ApiService provideApiService() {
    if(mockMode) {
        return new MockApiService();
    }
    else {
        Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                .create();
        return new RestAdapter.Builder()
                .setEndpoint(ApiService.API_URL)
                .setConverter(new GsonConverter(gson))
                .setLogLevel(RestAdapter.LogLevel.FULL).setLog(new AndroidLog("API"))
                .build()
                .create(ApiService.class);
    }
}
 
Example #18
Source File: Util.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 6 votes vote down vote up
public static Gson newGson() {
    return new GsonBuilder()
        .setPrettyPrinting()
        .setFieldNamingStrategy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .registerTypeAdapter(LocalDate.class, new TypeAdapter<LocalDate>() {
            @Override
            public void write(JsonWriter out, LocalDate value) throws IOException {
                out.value(value.toString());
            }

            @Override
            public LocalDate read(JsonReader in) throws IOException {
                return LocalDate.parse(in.nextString());
            }
        })
        .create();
}
 
Example #19
Source File: Util.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 6 votes vote down vote up
public static Gson newGson() {
    return new GsonBuilder()
        .setPrettyPrinting()
        .setFieldNamingStrategy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .registerTypeAdapter(LocalDate.class, new TypeAdapter<LocalDate>() {
            @Override
            public void write(JsonWriter out, LocalDate value) throws IOException {
                out.value(value.toString());
            }

            @Override
            public LocalDate read(JsonReader in) throws IOException {
                return LocalDate.parse(in.nextString());
            }
        })
        .create();
}
 
Example #20
Source File: Util.java    From Design-Patterns-and-SOLID-Principles-with-Java with MIT License 6 votes vote down vote up
public static Gson newGson() {
    return new GsonBuilder()
        .setPrettyPrinting()
        .setFieldNamingStrategy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .registerTypeAdapter(LocalDate.class, new TypeAdapter<LocalDate>() {
            @Override
            public void write(JsonWriter out, LocalDate value) throws IOException {
                out.value(value.toString());
            }

            @Override
            public LocalDate read(JsonReader in) throws IOException {
                return LocalDate.parse(in.nextString());
            }
        })
        .create();
}
 
Example #21
Source File: SpeechToTextWebSocketListener.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the start message.
 *
 * @param options the options
 * @return the request
 */
private String buildStartMessage(RecognizeOptions options) {
  Gson gson =
      new GsonBuilder()
          .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
          .create();
  JsonObject startMessage = new JsonParser().parse(gson.toJson(options)).getAsJsonObject();
  startMessage.remove(MODEL);
  startMessage.remove(CUSTOMIZATION_ID);
  startMessage.remove(LANGUAGE_CUSTOMIZATION_ID);
  startMessage.remove(ACOUSTIC_CUSTOMIZATION_ID);
  startMessage.remove(VERSION);
  startMessage.addProperty(ACTION, START);
  return startMessage.toString();
}
 
Example #22
Source File: NamingPolicyTest.java    From gson with Apache License 2.0 5 votes vote down vote up
public void testGsonWithLowerCaseUnderscorePolicyDeserialiation() {
  Gson gson = builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      .create();
  String target = "{\"some_constant_string_instance_field\":\"someValue\"}";
  StringWrapper deserializedObject = gson.fromJson(target, StringWrapper.class);
  assertEquals("someValue", deserializedObject.someConstantStringInstanceField);
}
 
Example #23
Source File: QuizSubmissionQuestionImpl.java    From canvas-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public QuizSubmissionQuestionWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    QuizSubmissionQuestionWrapper wrapper = new QuizSubmissionQuestionWrapper();
    if (json.getAsJsonObject().get("quiz_submission_questions").isJsonArray()) {
        JsonArray questionArray = json.getAsJsonObject().getAsJsonArray("quiz_submission_questions");
        List<QuizSubmissionQuestion> questionList = new LinkedList<>();
        for (JsonElement question : questionArray) {
            QuizSubmissionQuestion newQuestion = new QuizSubmissionQuestion();
            JsonObject questionObject = question.getAsJsonObject();
            newQuestion.setId(questionObject.has("id") ? questionObject.get("id").getAsInt() : null);
            newQuestion.setFlagged(questionObject.has("flagged") ? questionObject.get("flagged").getAsBoolean() : null);

            List<Integer> answerList = new LinkedList<>();
            if (questionObject.has("answer")) {
                if (questionObject.get("answer").isJsonArray()) {
                    for (JsonElement answer : questionObject.getAsJsonArray("answer")) {
                        answerList.add(answer.getAsInt());
                    }
                } else answerList.add(questionObject.get("answer").getAsInt());
            }
            newQuestion.setAnswer(answerList);

            Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
            Type listType = new TypeToken<List<QuizAnswer>>() {
            }.getType();
            newQuestion.setAnswers(gson.fromJson(questionObject.get("answers").toString(), listType));

            questionList.add(newQuestion);

        }
        wrapper.setQuizsubmissionquestions(questionList);
    }
    return wrapper;
}
 
Example #24
Source File: GeoApiContext.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
<T, R extends ApiResponse<T>> PendingResult<T> handlePost(
String hostName,
String url,
String payload,
String userAgent,
String experienceIdHeaderValue,
Class<R> clazz,
FieldNamingPolicy fieldNamingPolicy,
long errorTimeout,
Integer maxRetries,
ExceptionsAllowedToRetry exceptionsAllowedToRetry,
RequestMetrics metrics);
 
Example #25
Source File: TextToSpeechWebSocketListener.java    From java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Builds the start message.
 *
 * @param options the options
 * @return the request
 */
private String buildStartMessage(SynthesizeOptions options) {
  Gson gson =
      new GsonBuilder()
          .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
          .create();
  JsonObject startMessage = new JsonParser().parse(gson.toJson(options)).getAsJsonObject();

  // remove options that are already in query string
  startMessage.remove(VOICE);
  startMessage.remove(CUSTOMIZATION_ID);

  startMessage.addProperty(ACTION, START);
  return startMessage.toString();
}
 
Example #26
Source File: RetrofitModule.java    From MoxySample with MIT License 5 votes vote down vote up
@Provides
@Singleton
Gson provideGson() {
	return new GsonBuilder()
			.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
			.setFieldNamingStrategy(new CustomFieldNamingPolicy())
			.setPrettyPrinting()
			.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
			.serializeNulls()
			.create();
}
 
Example #27
Source File: RetrofitModule.java    From Moxy with MIT License 5 votes vote down vote up
@Provides
@Singleton
Gson provideGson() {
	return new GsonBuilder()
			.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
			.setFieldNamingStrategy(new CustomFieldNamingPolicy())
			.setPrettyPrinting()
			.setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
			.serializeNulls()
			.create();
}
 
Example #28
Source File: GoogleTaskApi.java    From SyncManagerAndroid-DemoGoogleTasks with MIT License 5 votes vote down vote up
public GoogleTaskApi(String authToken) {
	final String token = authToken;

	RequestInterceptor requestInterceptor = new RequestInterceptor() {
		  @Override
		  public void intercept(RequestFacade request) {
		    request.addHeader("Authorization", "Bearer "+token);
		  }
	};
	
	Gson gson = 
		    new GsonBuilder()
       			.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
		        .registerTypeAdapter(List.class, new TaskListDeserializer<List<TaskList>>())
		        .registerTypeAdapter(List.class, new TaskListDeserializer<List<Task>>())
		        .registerTypeAdapter(Task.class, new TaskTypeAdapter())
		        .create();

	mRestAdapter = new RestAdapter.Builder()
		.setRequestInterceptor(requestInterceptor)
		.setEndpoint(GoogleTaskApiService.API_BASE_URL)
		.setConverter(new GsonConverter(gson))
		.build();
			
	//Log.d(TAG, "retrofit log level:"+mRestAdapter.getLogLevel());
	//mRestAdapter.setLogLevel(LogLevel.FULL);
	//Log.d(TAG, "retrofit log level after setting full:"+mRestAdapter.getLogLevel());
	
	mService = mRestAdapter.create(GoogleTaskApiService.class);
}
 
Example #29
Source File: OkHttpRequestHandler.java    From google-maps-services-java with Apache License 2.0 5 votes vote down vote up
@Override
public <T, R extends ApiResponse<T>> PendingResult<T> handlePost(
    String hostName,
    String url,
    String payload,
    String userAgent,
    String experienceIdHeaderValue,
    Class<R> clazz,
    FieldNamingPolicy fieldNamingPolicy,
    long errorTimeout,
    Integer maxRetries,
    ExceptionsAllowedToRetry exceptionsAllowedToRetry,
    RequestMetrics metrics) {
  RequestBody body = RequestBody.create(JSON, payload);
  Request.Builder builder = new Request.Builder().post(body).header("User-Agent", userAgent);

  if (experienceIdHeaderValue != null) {
    builder = builder.header(HttpHeaders.X_GOOG_MAPS_EXPERIENCE_ID, experienceIdHeaderValue);
  }
  Request req = builder.url(hostName + url).build();

  return new OkHttpPendingResult<>(
      req,
      client,
      clazz,
      fieldNamingPolicy,
      errorTimeout,
      maxRetries,
      exceptionsAllowedToRetry,
      metrics);
}
 
Example #30
Source File: WebModule.java    From Qiitanium with MIT License 5 votes vote down vote up
@Singleton
@Provides
public Gson provideGson() {
  return new GsonBuilder()
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      .create();
}