com.google.gson.GsonBuilder Java Examples
The following examples show how to use
com.google.gson.GsonBuilder.
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: Config.java From js-dossier with Apache License 2.0 | 6 votes |
private static Gson createGsonParser(FileSystem fileSystem) { Path cwd = normalizedAbsolutePath(fileSystem, ""); return new GsonBuilder() .registerTypeAdapter(Config.class, new ConfigMarshaller(fileSystem)) .registerTypeAdapter(Path.class, new PathDeserializer(fileSystem)) .registerTypeAdapter(PathSpec.class, new PathSpecDeserializer(cwd)) .registerTypeAdapter(Pattern.class, new PatternDeserializer()) .registerTypeAdapter( new TypeToken<Optional<Path>>() {}.getType(), new OptionalDeserializer<>(Path.class)) .registerTypeAdapter( new TypeToken<Optional<String>>() {}.getType(), new OptionalDeserializer<>(String.class)) .registerTypeAdapter( new TypeToken<ImmutableSet<MarkdownPage>>() {}.getType(), new ImmutableSetDeserializer<>(MarkdownPage.class)) .registerTypeAdapter( new TypeToken<ImmutableSet<Path>>() {}.getType(), new ImmutableSetDeserializer<>(Path.class)) .registerTypeAdapter( new TypeToken<ImmutableSet<Pattern>>() {}.getType(), new ImmutableSetDeserializer<>(Pattern.class)) .create(); }
Example #2
Source File: IntegrationMockClient.java From product-private-paas with Apache License 2.0 | 6 votes |
public boolean terminateInstance(String instanceId) { try { if (log.isDebugEnabled()) { log.debug(String.format("Terminate instance: [instance-id] %s", instanceId)); } URI uri = new URIBuilder(endpoint + INSTANCES_CONTEXT + instanceId).build(); org.apache.stratos.mock.iaas.client.rest.HttpResponse response = doDelete(uri); if (response != null) { if ((response.getStatusCode() >= 200) && (response.getStatusCode() < 300)) { return true; } else { GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); org.apache.stratos.mock.iaas.domain.ErrorResponse errorResponse = gson.fromJson(response.getContent(), org.apache.stratos.mock.iaas.domain.ErrorResponse.class); if (errorResponse != null) { throw new RuntimeException(errorResponse.getErrorMessage()); } } } throw new RuntimeException("An unknown error occurred"); } catch (Exception e) { String message = "Could not start mock instance"; throw new RuntimeException(message, e); } }
Example #3
Source File: AfterRegistShareDialogActivity.java From Social with Apache License 2.0 | 6 votes |
private void handleGetShareInfo(Message msg){ String result = msg.obj.toString(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); ShareInfoRoot root = gson.fromJson(result, ShareInfoRoot.class); if (root == null){ //new Dialog(this,"错误","链接服务器失败").show(); Toast.makeText(this, "服务器繁忙,请重试", Toast.LENGTH_LONG).show(); return; } switch (share_type){ case 1: shareQqone(root.content, root.url, root.img_url); break; case 2: shareWechatMoment(root.content, root.url, root.img_url); break; case 3: shareSina(root.content, root.url, root.img_url); break; } }
Example #4
Source File: ApiClient.java From devicehive-java with Apache License 2.0 | 6 votes |
private void createDefaultAdapter(String url) { DateTimeTypeAdapter typeAdapter = new DateTimeTypeAdapter(Const.TIMESTAMP_FORMAT); Gson gson = new GsonBuilder() .registerTypeAdapter(DateTime.class, typeAdapter) .create(); okClient = new OkHttpClient().newBuilder() .readTimeout(35, TimeUnit.SECONDS) .connectTimeout(35, TimeUnit.SECONDS) .build(); if (!url.endsWith("/")) url = url + "/"; adapterBuilder = new Retrofit .Builder() .baseUrl(url) .client(okClient) .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonCustomConverterFactory.create(gson)); }
Example #5
Source File: RoleController.java From hauth-java with MIT License | 6 votes |
@RequestMapping(value = "/delete", method = RequestMethod.POST) public String delete(HttpServletResponse response, HttpServletRequest request) { String json = request.getParameter("JSON"); List<RoleEntity> list = new GsonBuilder().create().fromJson(json, new TypeToken<List<RoleEntity>>() { }.getType()); for (RoleEntity m : list) { AuthDTO authDTO = authService.domainAuth(request, m.getDomain_id(), "w"); if (!authDTO.getStatus()) { return Hret.error(403, "您没有权限删除域【" + m.getDomain_id() + "】中的角色信息", null); } } RetMsg retMsg = roleService.delete(list); if (!retMsg.checkCode()) { response.setStatus(retMsg.getCode()); return Hret.error(retMsg); } return Hret.success(retMsg); }
Example #6
Source File: Feature.java From mapbox-java with MIT License | 6 votes |
/** * This takes the currently defined values found inside this instance and converts it to a GeoJson * string. * * @return a JSON string which represents this Feature * @since 1.0.0 */ @Override public String toJson() { Gson gson = new GsonBuilder() .registerTypeAdapterFactory(GeoJsonAdapterFactory.create()) .registerTypeAdapterFactory(GeometryAdapterFactory.create()) .create(); // Empty properties -> should not appear in json string Feature feature = this; if (properties().size() == 0) { feature = new Feature(TYPE, bbox(), id(), geometry(), null); } return gson.toJson(feature); }
Example #7
Source File: BaseServiceCleanArch.java From CleanArchitecturePlugin with Apache License 2.0 | 6 votes |
public Retrofit getAdapter() { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(10, TimeUnit.SECONDS) .addInterceptor(new LoggingInterceptor()) .build(); Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC) .serializeNulls() .create(); return new Retrofit.Builder() .baseUrl(Constants.ENDPOINT) .client(client) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); }
Example #8
Source File: TwillRuntimeSpecificationAdapter.java From twill with Apache License 2.0 | 6 votes |
private TwillRuntimeSpecificationAdapter() { gson = new GsonBuilder() .serializeNulls() .registerTypeAdapter(TwillRuntimeSpecification.class, new TwillRuntimeSpecificationCodec()) .registerTypeAdapter(TwillSpecification.class, new TwillSpecificationCodec()) .registerTypeAdapter(TwillSpecification.Order.class, new TwillSpecificationOrderCoder()) .registerTypeAdapter(TwillSpecification.PlacementPolicy.class, new TwillSpecificationPlacementPolicyCoder()) .registerTypeAdapter(EventHandlerSpecification.class, new EventHandlerSpecificationCoder()) .registerTypeAdapter(RuntimeSpecification.class, new RuntimeSpecificationCodec()) .registerTypeAdapter(TwillRunnableSpecification.class, new TwillRunnableSpecificationCodec()) .registerTypeAdapter(ResourceSpecification.class, new ResourceSpecificationCodec()) .registerTypeAdapter(LocalFile.class, new LocalFileCodec()) .registerTypeAdapterFactory(new TwillSpecificationTypeAdapterFactory()) .create(); }
Example #9
Source File: AuthenticationInterceptor.java From EasyEE with MIT License | 6 votes |
/** * 设置当前用户的菜单 * * @param session * @param token */ public void initMenu(Session session, UsernamePasswordEncodeToken token) { // Set<SysMenuPermission> menus = new HashSet<SysMenuPermission>(); // Set<SysRole> roles = sysUser.getSysRoles(); // Roles // // 菜单权限 // for (SysRole role : roles) { // Set<SysMenuPermission> menuPermissions = // role.getSysMenuPermissions(); // for (SysMenuPermission menuPermission : menuPermissions) { // menus.add(menuPermission); // } // } List<SysMenuPermission> menus = sysMenuPermissionService.listByUserId(token.getUserId()); // 将菜单权限集合转为EasyUI菜单Tree List<EasyUITreeEntity> list = EasyUIUtil.getEasyUITreeFromUserMenuPermission(menus); Gson gson = new GsonBuilder().create(); String menuTreeJson = gson.toJson(list); // session.setAttribute("menus", menus); //菜单权限集合 info session.setAttribute("menuTreeJson", menuTreeJson); // 菜单权限集合 info }
Example #10
Source File: AgentManagementServiceImpl.java From Insights with Apache License 2.0 | 6 votes |
/** * Stores userid/pwd/token and aws credentials in vault engine as per agent. * * @param dataMap {eg: {"data":{"passwd":"password","userid":"userid"}}} * @param agentId * @return vaultresponse * @throws InsightsCustomException */ private ClientResponse storeToVault(HashMap<String, Map<String, String>> dataMap, String agentId) throws InsightsCustomException { ClientResponse vaultresponse = null; try { GsonBuilder gb = new GsonBuilder(); Gson gsonObject = gb.create(); String jsonobj = gsonObject.toJson(dataMap); log.debug("Request body for vault {} -- ", jsonobj); String url = ApplicationConfigProvider.getInstance().getVault().getVaultEndPoint() + ApplicationConfigProvider.getInstance().getVault().getSecretEngine() + "/data/" + agentId; log.debug("url {}--", url); WebResource resource = Client.create().resource(url); vaultresponse = resource.type("application/json") .header("X-Vault-Token", ApplicationConfigProvider.getInstance().getVault().getVaultToken()) .post(ClientResponse.class, jsonobj); } catch (Exception e) { log.error("Error while Storing to vault agent {} ", e); throw new InsightsCustomException(e.getMessage()); } return vaultresponse; }
Example #11
Source File: Utils.java From Tutorials with Apache License 2.0 | 6 votes |
public static List<Feed> loadFeeds(Context context){ try{ GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); JSONArray array = new JSONArray(loadJSONFromAsset(context, "news.json")); List<Feed> feedList = new ArrayList<>(); for(int i=0;i<array.length();i++){ Feed feed = gson.fromJson(array.getString(i), Feed.class); feedList.add(feed); } return feedList; }catch (Exception e){ Log.d(TAG,"seedGames parseException " + e); e.printStackTrace(); return null; } }
Example #12
Source File: TMDbClient.java From Amphitheatre with Apache License 2.0 | 6 votes |
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: TypeAdapterPrecedenceTest.java From gson with Apache License 2.0 | 5 votes |
public void testStreamingFollowedByNonstreaming() { Gson gson = new GsonBuilder() .registerTypeAdapter(Foo.class, newTypeAdapter("type adapter")) .registerTypeAdapter(Foo.class, newSerializer("serializer")) .registerTypeAdapter(Foo.class, newDeserializer("deserializer")) .create(); assertEquals("\"foo via serializer\"", gson.toJson(new Foo("foo"))); assertEquals("foo via deserializer", gson.fromJson("foo", Foo.class).name); }
Example #14
Source File: InstantConverterTest.java From gson-jodatime-serialisers with MIT License | 5 votes |
/** * Tests that the {@link Instant} can be round-tripped. */ @Test public void testRoundtrip() { final Gson gson = Converters.registerInstant(new GsonBuilder()).create(); final Instant ldt = new Instant(); assertThat(gson.fromJson(gson.toJson(ldt), Instant.class), is(ldt)); }
Example #15
Source File: BgReading.java From xDrip with GNU General Public License v3.0 | 5 votes |
public String toS() { Gson gson = new GsonBuilder() .excludeFieldsWithoutExposeAnnotation() .registerTypeAdapter(Date.class, new DateTypeAdapter()) .serializeSpecialFloatingPointValues() .create(); return gson.toJson(this); }
Example #16
Source File: LocationService.java From FineGeotag with GNU General Public License v3.0 | 5 votes |
public static String serialize(Location location) { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Location.class, new LocationSerializer()); Gson gson = builder.create(); String json = gson.toJson(location); return json; }
Example #17
Source File: Table.java From robot with BSD 3-Clause "New" or "Revised" License | 5 votes |
/** * Render the Table as a JSON string. * * @return JSON string */ public String toJSON() { JsonArray table = new JsonArray(); for (Row row : rows) { table.add(row.toJSON(columns)); } Gson gson = new GsonBuilder().setPrettyPrinting().disableHtmlEscaping().create(); return gson.toJson(table); }
Example #18
Source File: OAuthStoreHandlerImpl.java From openhab-core with Eclipse Public License 2.0 | 5 votes |
public StorageFacade(Storage<String> storage) { this.storage = storage; // Add adapters for LocalDateTime gson = new GsonBuilder() .registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, typeOfT, context) -> LocalDateTime .parse(json.getAsString())) .registerTypeAdapter(LocalDateTime.class, (JsonSerializer<LocalDateTime>) (date, type, jsonSerializationContext) -> new JsonPrimitive(date.toString())) .setPrettyPrinting().create(); }
Example #19
Source File: KmsKeyMgr.java From ranger with Apache License 2.0 | 5 votes |
public VXKmsKey getKeyFromUri(String provider, String name, boolean isKerberos, String repoName) throws Exception { Client c = getClient(); String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name); String currentUserLoginId = ContextUtil.getCurrentUserLoginId(); String uri = provider + (provider.endsWith("/") ? keyRest : ("/" + keyRest)); if(!isKerberos){ uri = uri.concat("?user.name="+currentUserLoginId); }else{ uri = uri.concat("?doAs="+currentUserLoginId); } final WebResource r = c.resource(uri); String response = null; if(!isKerberos){ response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); }else{ Subject sub = getSubjectForKerberos(repoName); response = Subject.doAs(sub, new PrivilegedAction<String>() { @Override public String run() { return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class); } }); } Gson gson = new GsonBuilder().create(); logger.debug("RESPONSE: [" + response + "]"); VXKmsKey key = gson.fromJson(response, VXKmsKey.class); return key; }
Example #20
Source File: RestCommandLineService.java From attic-stratos with Apache License 2.0 | 5 votes |
/** * Add user * * @param userName username * @param credential password * @param role user role * @param firstName first name * @param lastName last name * @param email email * @param profileName profile name * @throws CommandException */ public void addUser(String userName, String credential, String role, String firstName, String lastName, String email, String profileName) throws CommandException { DefaultHttpClient httpClient = new DefaultHttpClient(); try { UserInfoBean userInfoBean = new UserInfoBean(); userInfoBean.setUserName(userName); userInfoBean.setCredential(credential); userInfoBean.setRole(role); userInfoBean.setFirstName(firstName); userInfoBean.setLastName(lastName); userInfoBean.setEmail(email); userInfoBean.setProfileName(profileName); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); String jsonString = gson.toJson(userInfoBean, UserInfoBean.class); HttpResponse response = restClient.doPost(httpClient, restClient.getBaseURL() + ENDPOINT_ADD_USER, jsonString); String result = getHttpResponseString(response); System.out.println(gson.fromJson(result, ResponseMessageBean.class).getMessage()); } catch (Exception e) { String message = "Could not add user: " + userName; printError(message, e); } finally { httpClient.getConnectionManager().shutdown(); } }
Example #21
Source File: NullObjectAndFieldTest.java From gson with Apache License 2.0 | 5 votes |
public void testPrintPrintingObjectWithNulls() throws Exception { gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); String result = gson.toJson(new ClassWithMembers()); assertEquals("{}", result); gson = gsonBuilder.serializeNulls().create(); result = gson.toJson(new ClassWithMembers()); assertTrue(result.contains("\"str\":null")); }
Example #22
Source File: DynamodbEventSerializer.java From bender with Apache License 2.0 | 5 votes |
private Gson createGson() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Date.class, new DateAdapter()); builder.registerTypeAdapter( new TypeToken<Map<String, AttributeValue>>() {}.getType(), new AttributeValueMapAdapter()); return builder.create(); }
Example #23
Source File: FileBasedApplicationImportExportManager.java From carbon-apimgt with Apache License 2.0 | 5 votes |
/** * write the given Application details to file system * * @param application {@link Application} object to be exported * @param exportLocation file system location to write the Application Details * @throws IOException if an error occurs while writing the Application Details */ private void exportApplicationDetailsToFileSystem(Application application, String exportLocation) throws IOException { String applicationFileLocation = exportLocation + File.separator + application.getName() + APIConstants.JSON_FILE_EXTENSION; Gson gson = new GsonBuilder().setPrettyPrinting().create(); try (FileOutputStream fileOutputStream = new FileOutputStream(applicationFileLocation); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, StandardCharsets.UTF_8)) { gson.toJson(application, outputStreamWriter); } }
Example #24
Source File: LocalDateConverterTest.java From gson-javatime-serialisers with MIT License | 5 votes |
/** * Tests that serialising to JSON works. */ @Test public void testSerialisation() throws Exception { final Gson gson = registerLocalDate(new GsonBuilder()).create(); final LocalDate localDate = LocalDate.parse("1969-07-21"); final String json = gson.toJson(localDate); assertThat(json, is("\"1969-07-21\"")); }
Example #25
Source File: ApiModule.java From mockstar with MIT License | 5 votes |
@Provides @Singleton Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); }
Example #26
Source File: GsonUtils.java From AndroidUtilCode with Apache License 2.0 | 5 votes |
static Gson getGson4LogUtils() { Gson gson4LogUtils = GSONS.get(KEY_LOG_UTILS); if (gson4LogUtils == null) { gson4LogUtils = new GsonBuilder().setPrettyPrinting().serializeNulls().create(); GSONS.put(KEY_LOG_UTILS, gson4LogUtils); } return gson4LogUtils; }
Example #27
Source File: SecurityConfigurationGson.java From NFVO with Apache License 2.0 | 5 votes |
@Bean @Scope("prototype") Gson gson() { return new GsonBuilder() .setPrettyPrinting() .registerTypeAdapter(NFVMessage.class, new NfvoGsonDeserializerNFVMessage()) .registerTypeAdapter(BaseVimInstance.class, new NfvoGsonDeserializerVimInstance()) .registerTypeAdapter(BaseVimInstance.class, new NfvoGsonSerializerVimInstance()) .registerTypeAdapter(OAuth2AccessToken.class, new GsonSerializerOAuth2AccessToken()) .create(); }
Example #28
Source File: TypeAdapterPrecedenceTest.java From gson with Apache License 2.0 | 5 votes |
public void testNonstreamingHierarchicalFollowedByNonstreaming() { Gson gson = new GsonBuilder() .registerTypeHierarchyAdapter(Foo.class, newSerializer("hierarchical")) .registerTypeHierarchyAdapter(Foo.class, newDeserializer("hierarchical")) .registerTypeAdapter(Foo.class, newSerializer("non hierarchical")) .registerTypeAdapter(Foo.class, newDeserializer("non hierarchical")) .create(); assertEquals("\"foo via non hierarchical\"", gson.toJson(new Foo("foo"))); assertEquals("foo via non hierarchical", gson.fromJson("foo", Foo.class).name); }
Example #29
Source File: CalibrationAbstract.java From xDrip with GNU General Public License v3.0 | 5 votes |
protected static String dataToJsonString(CalibrationData data) { final Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); try { return gson.toJson(data); } catch (NullPointerException e) { return ""; } }
Example #30
Source File: InstantConverterTest.java From gson-jodatime-serialisers with MIT License | 5 votes |
/** * Tests that serialising an instant with out milliseconds returns the expected ISO 8601 string */ @Test public void testSerialiseWithOutMilliseconds() { final Gson gson = Converters.registerInstant(new GsonBuilder()).create(); final Instant instant = Instant.parse("2019-07-23T00:06:12Z"); final String expectedJson = "\"2019-07-23T00:06:12.000Z\""; final String actualJson = gson.toJson(instant); assertThat(actualJson, is(expectedJson)); }