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 Project: Design-Patterns-and-SOLID-Principles-with-Java   Author: PacktPublishing   File: Util.java    License: 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 #2
Source Project: Design-Patterns-and-SOLID-Principles-with-Java   Author: PacktPublishing   File: Util.java    License: 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 #3
Source Project: Design-Patterns-and-SOLID-Principles-with-Java   Author: PacktPublishing   File: Util.java    License: 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 #4
Source Project: sana.mobile   Author: SanaMobile   File: JSONTests.java    License: 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 #5
Source Project: Amphitheatre   Author: jerrellmardis   File: TMDbClient.java    License: 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 #6
Source Project: curiostack   Author: curioswitch   File: ArmeriaRequestHandler.java    License: 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 #7
Source Project: curiostack   Author: curioswitch   File: ArmeriaRequestHandler.java    License: 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 Project: curiostack   Author: curioswitch   File: ArmeriaRequestHandler.java    License: 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 #9
Source Project: google-maps-services-java   Author: googlemaps   File: OkHttpPendingResult.java    License: 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 #10
Source Project: Saiy-PS   Author: brandall76   File: ResolveNuance.java    License: 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 #11
Source Project: Saiy-PS   Author: brandall76   File: ResolveSaiy.java    License: 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 #12
Source Project: synthea   Author: synthetichealth   File: Attributes.java    License: 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 #13
Source Project: android-test-demo   Author: abdyer   File: DebugApiServiceModule.java    License: 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 #14
Source Project: google-maps-services-java   Author: googlemaps   File: GaePendingResult.java    License: 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 #15
Source Project: cosmic   Author: MissionCriticalCloud   File: NatRuleTest.java    License: 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 #16
Source Project: intellij-swagger   Author: zalando   File: HttpZallyService.java    License: 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 #17
Source Project: SyncManagerAndroid-DemoGoogleTasks   Author: sschendel   File: GoogleTaskApi.java    License: 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 #18
Source Project: fluo   Author: apache   File: ScanUtil.java    License: 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 #19
Source Project: quill   Author: vickychijwani   File: GhostApiUtils.java    License: 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 #20
Source Project: udacity-p1-p2-popular-movies   Author: vickychijwani   File: Model.java    License: 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 #21
Source Project: Qiitanium   Author: ogaclejapan   File: WebModule.java    License: MIT License 5 votes vote down vote up
@Singleton
@Provides
public Gson provideGson() {
  return new GsonBuilder()
      .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
      .create();
}
 
Example #22
Source Project: uyuni   Author: uyuni-project   File: MatcherJsonIO.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #23
Source Project: p2   Author: iNPUTmice   File: FcmPushService.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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);
}
 
Example #24
Source Project: lbry-android   Author: lbryio   File: Lbryio.java    License: MIT License 5 votes vote down vote up
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;
    }
}
 
Example #25
Source Project: lbry-android   Author: lbryio   File: LbryFile.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example #26
Source Project: lbry-android   Author: lbryio   File: Claim.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example #27
Source Project: AndroidBlueprints   Author: davideas   File: ApiModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
GsonConverterFactory provideGsonConverter() {
    return GsonConverterFactory.create(
            new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create());
}
 
Example #28
Source Project: AndroidBlueprints   Author: davideas   File: ApiModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
GsonConverterFactory provideGsonConverter() {
    return GsonConverterFactory.create(
            new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create());
}
 
Example #29
Source Project: auto-matter   Author: danielnorberg   File: AutoMatterTypeAdapterFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@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
}
 
Example #30
Source Project: AndroidBlueprints   Author: davideas   File: ApiModule.java    License: Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
GsonConverterFactory provideGsonConverter() {
    return GsonConverterFactory.create(
            new GsonBuilder()
                    .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
                    .create());
}