类com.google.gson.FieldNamingPolicy源码实例Demo

下面列出了怎么用com.google.gson.FieldNamingPolicy的API类实例代码及写法,或者点击链接到github查看源代码。

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();
}
 
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();
}
 
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();
}
 
源代码4 项目: sana.mobile   文件: JSONTests.java
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);
}
 
源代码5 项目: Amphitheatre   文件: TMDbClient.java
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;
}
 
源代码6 项目: curiostack   文件: ArmeriaRequestHandler.java
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());
}
 
源代码7 项目: curiostack   文件: ArmeriaRequestHandler.java
@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);
}
 
源代码8 项目: curiostack   文件: ArmeriaRequestHandler.java
@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);
}
 
/**
 * @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);
}
 
源代码10 项目: Saiy-PS   文件: ResolveNuance.java
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();
}
 
源代码11 项目: Saiy-PS   文件: ResolveSaiy.java
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();
}
 
源代码12 项目: synthea   文件: Attributes.java
/**
 * 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.");
}
 
源代码13 项目: android-test-demo   文件: DebugApiServiceModule.java
@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);
    }
}
 
/**
 * @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);
}
 
源代码15 项目: cosmic   文件: NatRuleTest.java
@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));
}
 
源代码16 项目: intellij-swagger   文件: HttpZallyService.java
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);
}
 
@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);	
       
}
 
源代码18 项目: fluo   文件: ScanUtil.java
/**
 * 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();
}
 
源代码19 项目: quill   文件: GhostApiUtils.java
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();
}
 
源代码20 项目: udacity-p1-p2-popular-movies   文件: Model.java
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);
}
 
源代码21 项目: Qiitanium   文件: WebModule.java
@Singleton
@Provides
public Gson provideGson() {
  return new GsonBuilder()
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      .create();
}
 
源代码22 项目: uyuni   文件: MatcherJsonIO.java
/**
 * Constructor
 */
public MatcherJsonIO() {
    gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
        .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        .setPrettyPrinting()
        .create();

    s390arch = ServerFactory.lookupServerArchByLabel("s390x");

    productIdForS390xSystem = productIdForEntitlement("SUSE-Manager-Mgmt-Unlimited-Virtual-Z");
    productIdForSystem = productIdForEntitlement("SUSE-Manager-Mgmt-Single");
    lifecycleProductsTranslation = new HashMap<>();
    productIdForEntitlement("SUSE-Manager-Mgmt-Unlimited-Virtual").ifPresent(
            from -> productIdForSystem.ifPresent(to -> lifecycleProductsTranslation.put(from, to)));

    monitoringProductId = productIdForEntitlement("SUSE-Manager-Mon-Single");
    monitoringProductIdS390x = productIdForEntitlement("SUSE-Manager-Mon-Unlimited-Virtual-Z");
    productIdForEntitlement("SUSE-Manager-Mon-Unlimited-Virtual").ifPresent(
            from -> monitoringProductId.ifPresent(to -> lifecycleProductsTranslation.put(from, to)));

    selfProductsByArch = new HashMap<>();
    selfProductsByArch.put(AMD64_ARCH_STR, 1899L);   // SUSE Manager Server 4.0 x86_64
    selfProductsByArch.put(S390_ARCH_STR, 1898L);    // SUSE Manager Server 4.0 s390
    selfProductsByArch.put(PPC64LE_ARCH_STR, 1897L); // SUSE Manager Server 4.0 ppc64le

    monitoringProductByArch = new HashMap<>();
    monitoringProductByArch.put(AMD64_ARCH_STR, 1201L);   // SUSE Manager Monitoring Single
    monitoringProductByArch.put(S390_ARCH_STR, 1203L);    // SUSE Manager Monitoring Unlimited Virtual Z
    monitoringProductByArch.put(PPC64LE_ARCH_STR, 1201L); // SUSE Manager Monitoring Single

    productFactory = new CachingSUSEProductFactory();
}
 
源代码23 项目: p2   文件: FcmPushService.java
public FcmPushService() {
    final GsonBuilder gsonBuilder = new GsonBuilder();
    Adapter.register(gsonBuilder);
    gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);

    final Retrofit.Builder retrofitBuilder = new Retrofit.Builder();
    retrofitBuilder.baseUrl(BASE_URL);
    retrofitBuilder.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()));

    final Retrofit retrofit = retrofitBuilder.build();

    this.httpInterface = retrofit.create(FcmHttpInterface.class);
}
 
源代码24 项目: lbry-android   文件: Lbryio.java
public static User fetchCurrentUser(Context context) {
    try {
        Response response = Lbryio.call("user", "me", context);
        JSONObject object = (JSONObject) parseResponse(response);
        Type type = new TypeToken<User>(){}.getType();
        Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
        User user = gson.fromJson(object.toString(), type);
        return user;
    } catch (LbryioRequestException | LbryioResponseException | ClassCastException | IllegalStateException ex) {
        LbryAnalytics.logError(String.format("/user/me failed: %s", ex.getMessage()), ex.getClass().getName());
        android.util.Log.e(TAG, "Could not retrieve the current user", ex);
        return null;
    }
}
 
源代码25 项目: lbry-android   文件: LbryFile.java
public static LbryFile fromJSONObject(JSONObject fileObject) {
    String fileJson = fileObject.toString();
    Type type = new TypeToken<LbryFile>(){}.getType();
    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    LbryFile file = gson.fromJson(fileJson, type);

    if (file.getMetadata() != null && file.getMetadata().getReleaseTime() == 0) {
        file.getMetadata().setReleaseTime(file.getTimestamp());
    }
    return file;
}
 
源代码26 项目: lbry-android   文件: Claim.java
public static Claim fromJSONObject(JSONObject claimObject) {
    Claim claim = null;
    String claimJson = claimObject.toString();
    Type type = new TypeToken<Claim>(){}.getType();
    Type streamMetadataType = new TypeToken<StreamMetadata>(){}.getType();
    Type channelMetadataType = new TypeToken<ChannelMetadata>(){}.getType();

    Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    claim = gson.fromJson(claimJson, type);

    try {
        String valueType = claim.getValueType();
        // Specific value type parsing
        if (TYPE_REPOST.equalsIgnoreCase(valueType)) {
            JSONObject repostedClaimObject = claimObject.getJSONObject("reposted_claim");
            claim.setRepostedClaim(Claim.fromJSONObject(repostedClaimObject));
        } else {
            JSONObject value = claimObject.getJSONObject("value");
            if (value != null) {
                String valueJson = value.toString();
                if (TYPE_STREAM.equalsIgnoreCase(valueType)) {
                    claim.setValue(gson.fromJson(valueJson, streamMetadataType));
                } else if (TYPE_CHANNEL.equalsIgnoreCase(valueType)) {
                    claim.setValue(gson.fromJson(valueJson, channelMetadataType));
                }
            }
        }
    } catch (JSONException ex) {
        // pass
    }

    return claim;
}
 
源代码27 项目: AndroidBlueprints   文件: ApiModule.java
@Provides
@Singleton
GsonConverterFactory provideGsonConverter() {
    return GsonConverterFactory.create(
            new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create());
}
 
源代码28 项目: AndroidBlueprints   文件: ApiModule.java
@Provides
@Singleton
GsonConverterFactory provideGsonConverter() {
    return GsonConverterFactory.create(
            new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create());
}
 
@Test
public void testSerializedNameWithUnderscorePolicy() throws IOException {
  gson = new GsonBuilder()
      .registerTypeAdapterFactory(new AutoMatterTypeAdapterFactory())
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      .create();
  final String json = gson.toJson(BAR); //isPrivate -> private
  final Bar parsed = gson.fromJson(json, Bar.class); //private -> isPrivate
  assertThat(parsed, is(BAR));
  //Make sure that tranlation of under_scored fields still work.
  final String underscoredIsPrivate = "{\"a\":17,\"b\":\"foobar\",\"is_private\":true}";
  assertThat(gson.fromJson(underscoredIsPrivate, Bar.class), is(BAR)); //is_private -> isPrivate
}
 
源代码30 项目: AndroidBlueprints   文件: ApiModule.java
@Provides
@Singleton
GsonConverterFactory provideGsonConverter() {
    return GsonConverterFactory.create(
            new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create());
}
 
 类所在包
 类方法
 同包方法