@Provides public RedditResource provideRedditResource() { Type redditPostListType = new TypeToken<List<RedditPost>>() {}.getType(); Gson gson = new GsonBuilder() .registerTypeAdapter(redditPostListType, new RedditPostsDeserializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://www.reddit.com/") .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit.create(RedditResource.class); }
public T httpsPost(String jsonBody, Class<T> clazz) throws IOException { URL url = new URL(HTTPS_PROTOCOL, ACCOUNT_KEY_SERVICE_HOST, HTTPS_PORT, ACCOUNT_KEY_ENDPOINT); httpsConnection = (HttpsURLConnection) url.openConnection(); httpsConnection.setRequestMethod(HttpRequestMethod.POST.toString()); setConnectionParameters(httpsConnection, HttpRequestMethod.POST); httpsConnection.setFixedLengthStreamingMode(jsonBody.getBytes().length); try (OutputStreamWriter out = new OutputStreamWriter( httpsConnection.getOutputStream())) { out.write(jsonBody); } StringBuilder sb = new StringBuilder(); try (BufferedReader in = new BufferedReader(new InputStreamReader( httpsConnection.getInputStream()))) { String inputLine; while ((inputLine = in.readLine()) != null) { sb.append(inputLine); } } // setFieldNamingPolicy is used to here to convert from // lower_case_with_underscore names retrieved from end point to camel // case to match POJO class Gson gson = new GsonBuilder().setFieldNamingPolicy( FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); return gson.fromJson(sb.toString(), clazz); }
@Test public void testKfVideoMessageJson(){ Video video = new Video(); video.setMediaId("MEDIA_ID"); video.setThumbMediaId("MEDIA_ID"); video.setTitle("TITLE"); video.setDescription("DESCRIPTION"); CustomVideoMessage videoMsg = new CustomVideoMessage(); videoMsg.setTouser("OPENID"); videoMsg.setVideo(video); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); //System.out.println(gson.toJson(videoMsg)); String str = gson.toJson(videoMsg); Assert.assertNotNull(gson.fromJson(str, CustomVideoMessage.class)); }
@Test public void testKfMusicMessageJson(){ Music music = new Music(); music.setTitle("MUSIC_TITLE"); music.setDescription("MUSIC_DESCRIPTION"); music.setMusicurl("MUSIC_URL"); music.setHqmusicurl("HQ_MUSIC_URL"); music.setThumbMediaId("THUMB_MEDIA_ID"); CustomMusicMessage musicMsg = new CustomMusicMessage(); musicMsg.setTouser("OPENID"); musicMsg.setMusic(music); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); //System.out.println(gson.toJson(musicMsg)); String str = gson.toJson(musicMsg); Assert.assertNotNull(gson.fromJson(str, CustomMusicMessage.class)); }
@Test public void testKfNewsMessage(){ List<Article> articles = new ArrayList<Article>(); Article a1 = new Article(); a1.setTitle("Happy Day"); a1.setDescription("Is Really A Happy Day"); a1.setUrl("URL"); a1.setPicurl("PIC_URL"); articles.add(a1); Article a2 = new Article(); a2.setTitle("Happy Day"); a2.setDescription("Is Really A Happy Day"); a2.setUrl("URL"); a2.setPicurl("PIC_URL"); articles.add(a2); CustomNewsMessage newsMsg = new CustomNewsMessage(); newsMsg.setTouser("OPENID"); newsMsg.setNews(new News(articles)); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); //System.out.println(gson.toJson(newsMsg)); String str = gson.toJson(newsMsg); Assert.assertNotNull(gson.fromJson(str, CustomNewsMessage.class)); }
@Test public void testMapJson(){ Map<String, Media> map = new HashMap<String, Media>(); Media media = new Media(); media.setMediaId("mediaId"); media.setThumbMediaId("thumbMediaId"); media.setType("news"); media.setCreatedAt(1892391); map.put("template_id_short", media); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); //System.out.println(gson.toJson(newsMsg)); String jsonStr = gson.toJson(map); gson.fromJson(jsonStr, HashMap.class); }
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(); }
@Nullable public static Course getCourse(String zipFilePath) { try { final JBZipFile zipFile = new JBZipFile(zipFilePath); final JBZipEntry entry = zipFile.getEntry(EduNames.COURSE_META_FILE); if (entry == null) { return null; } byte[] bytes = entry.getData(); final String jsonText = new String(bytes, CharsetToolkit.UTF8_CHARSET); Gson gson = new GsonBuilder() .registerTypeAdapter(Task.class, new StudySerializationUtils.Json.TaskAdapter()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); return gson.fromJson(jsonText, Course.class); } catch (IOException e) { LOG.error("Failed to unzip course archive"); LOG.error(e); } return null; }
@Nullable private static StepicWrappers.TokenInfo getTokens(@NotNull final List<NameValuePair> parameters) { final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); final HttpPost request = new HttpPost(EduStepicNames.TOKEN_URL); request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8)); try { final CloseableHttpClient client = EduStepicClient.getHttpClient(); final CloseableHttpResponse response = client.execute(request); final StatusLine statusLine = response.getStatusLine(); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; EntityUtils.consume(responseEntity); if (statusLine.getStatusCode() == HttpStatus.SC_OK) { return gson.fromJson(responseString, StepicWrappers.TokenInfo.class); } else { LOG.warn("Failed to get tokens: " + statusLine.getStatusCode() + statusLine.getReasonPhrase()); } } catch (IOException e) { LOG.warn(e.getMessage()); } return null; }
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(); }
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(); }
public Gson create() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Id.class, new IdSerializer()); gsonBuilder.registerTypeAdapter(Type.class, new TypeSerializer()); gsonBuilder.registerTypeAdapter(Visitor.class, new VisitorSerializer()); gsonBuilder.registerTypeAdapter(Session.class, new SessionSerializer()); gsonBuilder.registerTypeAdapter(Map.class, new MapSerializer()); gsonBuilder.registerTypeAdapter(Payload.class, new MapSerializer()); gsonBuilder.serializeNulls(); gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); gsonBuilder.setLongSerializationPolicy(LongSerializationPolicy.STRING); gsonBuilder.enableComplexMapKeySerialization(); return gsonBuilder.create(); }
@VisibleForTesting public StackApi build(String apiHost, Interceptor idlingInterceptor) { OkHttpClient.Builder clientBuilder = new OkHttpClient.Builder() .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)); if (idlingInterceptor != null) { clientBuilder.addInterceptor(idlingInterceptor); } return new Retrofit.Builder() .baseUrl(apiHost) .client(clientBuilder.build()) .addConverterFactory(GsonConverterFactory.create( new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create() )) .addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())) .build() .create(StackApi.class); }
@Override public ArrayList<PDBrand> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.has("brands")) { Gson gson = new GsonBuilder() .registerTypeAdapter(PDBrand.class, new PDBrandDeserializer()) .registerTypeAdapter(long.class, new PDLongDeserializer()) .registerTypeAdapter(int.class, new PDIntDeserializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); JsonArray brandsArray = jsonObject.getAsJsonArray("brands"); return gson.fromJson(brandsArray, typeOfT); } return new ArrayList<>(); }
@Override public PDSocialMediaFriend deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); JsonObject jsonObject = json.getAsJsonObject(); PDSocialMediaFriend friend = gson.fromJson(jsonObject, PDSocialMediaFriend.class); if (jsonObject.has("picture")) { JsonObject pictureObject = jsonObject.getAsJsonObject("picture"); if (pictureObject.has("data")) { JsonObject pictureDataObject = pictureObject.getAsJsonObject("data"); friend.setImageUrl(pictureDataObject.get("url").getAsString()); } } return friend; }
@Override public PDLocation deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new GsonBuilder() .registerTypeAdapter(long.class, new PDLongDeserializer()) .registerTypeAdapter(int.class, new PDIntDeserializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); JsonObject jsonObject = json.getAsJsonObject(); PDLocation location = gson.fromJson(jsonObject, PDLocation.class); if (jsonObject.has("brand")) { JsonObject brandObject = jsonObject.getAsJsonObject("brand"); location.setBrandIdentifier(brandObject.get("id").getAsString()); location.setBrandName(brandObject.get("name").getAsString()); } return location; }
private static <T> T getFromStepic(String link, final Class<T> container) throws IOException { final HttpGet request = new HttpGet(stepicApiUrl + link); if (ourClient == null) { initializeClient(); } setHeaders(request, "application/json"); final CloseableHttpResponse response = ourClient.execute(request); final StatusLine statusLine = response.getStatusLine(); final HttpEntity responseEntity = response.getEntity(); final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : ""; if (statusLine.getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Stepic returned non 200 status code " + responseString); } Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); return gson.fromJson(responseString, container); }
private RedditAuthAPI buildApi(String baseUrl, boolean loggingEnabled) { OkHttpClient.Builder okhttp = new OkHttpClient.Builder() .addNetworkInterceptor(new UserAgentInterceptor(userAgent)) .addNetworkInterceptor(getHttpAuthInterceptor()); if (loggingEnabled) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); okhttp.addInterceptor(loggingInterceptor); } Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); Retrofit restAdapter = new Retrofit.Builder() .client(okhttp.build()) .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); return restAdapter.create(RedditAuthAPI.class); }
public MattermostEmitter(String scheme, String host, String channel) { this.scheme = scheme; this.host = host; this.channel = channel; this.gson = new GsonBuilder().disableHtmlEscaping() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setPrettyPrinting() .serializeNulls().create(); this.client = new OkHttpClient(); this.client.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); }
/** * parses the response of second call to T1AS creative assets approve api call. * * @param pResponse * requires a response string. * @return JsonResponse<? extends T1Entity> returns an entity of type T. */ public JsonResponse<? extends T1Entity> parseTOneASCreativeAssetsApproveResponse( String pResponse) { JsonResponse<? extends T1Entity> response; GsonBuilder builder = new GsonBuilder(); builder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_DASHES); builder.setDateFormat(YYYY_MM_DD_T_HH_MM_SS); Gson gson = builder.create(); Type type = new TypeToken<JsonResponse<ArrayList<TOneASCreativeAssetsApproveResponse>>>() { }.getType(); response = gson.fromJson(pResponse, type); return response; }
@SmallTest public void testIssueHashSerializer() { IssueHash issueHash = new IssueHash(); Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).registerTypeAdapter(IssueHash.class, new IssueHashSerializer()).create(); String json = gson.toJson(issueHash, IssueHash.class); assertEquals(json, "{}"); issueHash.subject = "Muj tiket"; json = gson.toJson(issueHash, IssueHash.class); assertTrue(json.contains("subject")); issueHash.subject = null; json = gson.toJson(issueHash, IssueHash.class); assertFalse(json.contains("subject")); issueHash.customFields = new ArrayList<>(); json = gson.toJson(issueHash, IssueHash.class); assertFalse(json.contains("custom_fields")); issueHash.customFields.add(new CustomField()); json = gson.toJson(issueHash, IssueHash.class); assertTrue(json.contains("custom_fields")); }
private static void initGlobalObjects(Context context, Options options) { GlobalObjectRegistry.addObject(OpenHelperManager.getHelper(context, DatabaseHelper.class)); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE) .create(); GlobalObjectRegistry.addObject(gson); ImageLoader.init(context); EmbeddedSocialServiceProvider serviceProvider = new EmbeddedSocialServiceProvider(context); GlobalObjectRegistry.addObject(EmbeddedSocialServiceProvider.class, serviceProvider); GlobalObjectRegistry.addObject(new Preferences(context)); GlobalObjectRegistry.addObject(new RequestInfoProvider(context)); GlobalObjectRegistry.addObject(new UserAccount(context)); GlobalObjectRegistry.addObject(new NotificationController(context)); NetworkAvailability networkAccessibility = new NetworkAvailability(); networkAccessibility.startMonitoring(context); GlobalObjectRegistry.addObject(networkAccessibility); FacebookSdk.sdkInitialize(context); FacebookSdk.setApplicationId(options.getFacebookApplicationId()); }
public static void main(String[] args) { System.out.println("==============upload resource demo==============="); UploadRes up = new UploadRes(); XVod xVod=new XVod("http://www.baidu.com"); // 设置回调url,自己指定url // json序列化和反序列化 Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); String vodStr=gson.toJson(xVod); System.out.println(vodStr); Map<String,Object> pmap=new HashMap<String, Object>(); pmap.put("x:vod",vodStr); pmap.put("key","you set your file key"); Map<String, Object> res = up.uploadResource("your hub name", 3600 * 7,null, "your video file local address", pmap); // 遍历上传资源后返回的结果 Set<String> set = res.keySet(); for (Iterator<String> it = set.iterator(); it.hasNext(); ) { String key = it.next(); System.out.println(key + " : " + res.get(key)); } }
/*** * PUT /v1/hubs/<Hub>/ad/images/<AdId> */ public boolean updateImageAd(String hub, String adId, ImageAdArgs args) { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); String bodyStr = gson.toJson(args); String rawUrl = Const.HOST + "/v1/hubs/" + hub + "/ad/images/" + adId; String auth = httpClient.getHttpRequestSign("PUT", rawUrl, bodyStr, true); Map<String, Object> ret = httpClient.doRequest("PUT", rawUrl, bodyStr, true, auth); if ((Integer) ret.get("code") == 200) { return true; } System.out.println("http response status:" + ret.get("code") + " error"); return false; }
/** * POST /v1/hubs/<Hub>/domains */ public boolean createCustomDomain(String hub, CustomDomainArgs args) { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); String bodyStr = gson.toJson(args); String rawUrl = Const.HOST + "/v1/hubs/" + hub + "/domains"; String auth = httpClient.getHttpRequestSign("POST", rawUrl, bodyStr, true); Map<String, Object> ret = httpClient.doRequest("POST", rawUrl, bodyStr, true, auth); if ((Integer) ret.get("code") == 200) { return true; } System.out.println("http response status:" + ret.get("code") + " error"); return false; }
/** * PUT /v1/hubs/<Hub>/ad/videos/<AdId> */ public boolean updateVideoAdConf(VideoAdInfo videoAdInfo, String hub, String adId) { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); String bodyStr = gson.toJson(videoAdInfo); String rawUrl = Const.HOST + "/v1/hubs/" + hub + "/ad/videos/" + adId; String auth = httpClient.getHttpRequestSign("PUT", rawUrl, bodyStr, true); Map<String, Object> ret = httpClient.doRequest("PUT", rawUrl, bodyStr, true, auth); if ((Integer) ret.get("code") == 200) { return true; } System.out.println("http response status:" + ret.get("code") + " error"); return false; }
public TestMyModule(@NonNull Context context) { super(context); mContext = context; mRenamingDelegatingContext = new RenamingDelegatingContext(mContext, "test_"); mMockWebServer = new MockWebServer(); mMockWebServer.setDispatcher(new AssetsDispatcher()); mSharedPreferences = mContext.getSharedPreferences("test_" + Constants.PREF_NAME, Context.MODE_PRIVATE); mMySQLiteOpenHelper = new MySQLiteOpenHelper(mRenamingDelegatingContext, Constants.DB_NAME, null, Constants.DB_VERSION); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); mRetrofit = new Retrofit.Builder() .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .baseUrl(mMockWebServer.url("/").toString()).build(); mGitHubService = mRetrofit.create(GitHubService.class); }
/** * Get a Gson object, preconfigured to load the GMF modules into classes. * * @return Gson object to unmarshal GMF JSON into objects */ public static Gson getGson() { return new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapterFactory(InnerClassTypeAdapterFactory.of(Logic.class,"condition_type")) .registerTypeAdapterFactory(InnerClassTypeAdapterFactory.of(State.class, "type")) .create(); }
@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(); }
private Gson createGson() { return new GsonBuilder() .registerTypeAdapter(Date.class, new ISO8601DateAdapter()) .registerTypeAdapter(CaseLock.class, CaseLock.TYPE_ADAPTER) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); }
@Provides @Singleton public Gson provideGson(){ return new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setLenient().setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create(); }
public static GsonBuilder gsonBuilder() { return new GsonBuilder() // Property visibility .serializeNulls() .setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { return false; } }) .excludeFieldsWithModifiers(Modifier.PROTECTED) .excludeFieldsWithoutExposeAnnotation() // Property naming and order .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setFieldNamingStrategy((field) -> field.getName().toLowerCase()) // Customised de/serializers // Formats, locals, encoding, binary data .setDateFormat("MM/dd/yyyy") .setPrettyPrinting(); }
public static Gson newGson() { final GsonBuilder gsonBuilder = new GsonBuilder() .registerTypeAdapter(ObjectId.class, new ObjectIdSerializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setPrettyPrinting() .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); // ISO 8601 return gsonBuilder.create(); }
public static Guideline fromGdl2(String guidelineInGDL2Format) { GsonBuilder gsonBuilder = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(ExpressionItem.class, new ExpressionItemDeserializer()) .registerTypeAdapter(CodePhrase.class, new CodePhraseDeserializer()); Gson gson = gsonBuilder.create(); return gson.fromJson(guidelineInGDL2Format, Guideline.class); }
public static String toGdl2(Guideline guideline) { Gson gson = new GsonBuilder() .registerTypeHierarchyAdapter(List.class, new ListSerializer()) .registerTypeHierarchyAdapter(Map.class, new MapSerializer()) .registerTypeAdapter(DataBinding.class, new DataBindingSerializer()) .registerTypeAdapter(CodePhrase.class, new CodePhraseSerializer()) .registerTypeAdapter(GuideDefinition.class, new GuideDefinitionSerializer()) .registerTypeAdapter(Rule.class, new RuleSerializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .setPrettyPrinting() .disableHtmlEscaping() .create(); return gson.toJson(guideline); }
@Provides @Singleton public Gson provideGson() { return new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); }
@Provides @Singleton public Gson provideGson() { return new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) .create(); }
/** * 群发消息预览 * @param accessToken * @param message * @param touser 公众号的openid * @param towxname 微信号 * @return */ public MassReturnCode preview(String accessToken, MassMessage message, String touser, String towxname) { Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); String msgText = gson.toJson(message); @SuppressWarnings("unchecked") Map<String, Object> msgMap = gson.fromJson(msgText, HashMap.class); if(msgMap.get("filter")!=null){ msgMap.remove("filter"); } if(msgMap.get("touser")!=null){ msgMap.remove("touser"); } if(msgMap.get("send_ignore_reprint")!=null){ msgMap.remove("send_ignore_reprint"); } if(towxname!=null){ msgMap.put("towxname", towxname); }else if(touser!=null){ msgMap.put("touser", touser); }else{ throw new IllegalArgumentException("群发消息预览参数不符合要求,touser和towxname不能都为空。"); } String url = WEIXIN_MASS_MESSAGE_PREVIEW_LINK + "?access_token=" + accessToken; return WeixinInterfaceHelper.post(url, msgMap, MassReturnCode.class); }
@Test public void testKfImageMessageJson(){ Image image = new Image(); image.setMediaId("MEDIA_ID"); CustomImageMessage imageMsg = new CustomImageMessage(); imageMsg.setTouser("OPENID"); imageMsg.setImage(image); Gson gson = new GsonBuilder() .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); //System.out.println(gson.toJson(imageMsg)); String str = gson.toJson(imageMsg); Assert.assertNotNull(gson.fromJson(str, CustomImageMessage.class)); }
public static TmdbService call() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); Gson gson = gsonBuilder.create(); OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); HttpUrl url = request.url().newBuilder() .addQueryParameter("api_key", API_KEY) .build(); request = request.newBuilder().url(url).build(); return chain.proceed(request); } }).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit.create(TmdbService.class); }