private <T> JsonResponse<T> commandResponse(String command, Type type) throws Exception { URI uri = this.getServerUri(command); // URI uri = new URI( serverUri.toString() + URLEncoder.encode(command) ); HttpURLConnection server = null; if (https) { server = (HttpsURLConnection) uri.toURL().openConnection(); } else { server = (HttpURLConnection) uri.toURL().openConnection(); } server.setConnectTimeout(30000); BufferedReader reader = new BufferedReader(new InputStreamReader(server.getInputStream())); // TypeToken cannot figure out T so instead it must be supplied // Type type = new TypeToken< JSONResponse<T> >() {}.getType(); GsonBuilder build = new GsonBuilder(); StringBuilder sBuild = new StringBuilder(); String input; while ((input = reader.readLine()) != null) sBuild.append(input); reader.close(); input = sBuild.toString(); build.registerTypeAdapter(JsonBoolean.class, new JsonBooleanDeserializer()); JsonResponse<T> response = null; try { response = build.create().fromJson(input, type); tryExtractError(response); return response; } catch (Exception e) { // well something messed up // if this part messes up then something REALLY bad happened response = build.create().fromJson(input, new TypeToken<JsonResponse<Object>>() {}.getType()); tryExtractError(response); // DO NOT RETURN AN ACTUAL OBJECT!!!!! // this makes the code in the UI confused return null; } }
static { GsonBuilder builder = new GsonBuilder(); builder.setPrettyPrinting(); builder.registerTypeAdapterFactory(new LowerCaseEnumTypeAdapterFactory()); builder.registerTypeAdapter(Date.class, new DateTypeAdapter()); builder.enableComplexMapKeySerialization(); mojangGson = builder.create(); builder = new GsonBuilder(); builder.setPrettyPrinting(); gson = builder.create(); }
@Override public void onResponse(GsonResult response, String tag) { super.onResponse(response, tag); if (TAG_API_GET_ACTIVITY_ON_GOING.equals(tag)) { JSONObject jsonObject = JsonUtil.getJSONObject(response.getJsonStr()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yyyy-MM-dd hh:mm:ss"); Gson gson = gsonBuilder.create(); Type listType = new TypeToken<List<HiActivity>>() {}.getType(); List<HiActivity> hiActivities = gson.fromJson(JsonUtil.getJSONArray(jsonObject, "list").toString(), listType); if (hiActivities != null) { mHiActivityAdapter.addAll(hiActivities); if (hiActivities.size() > 2) { mViewPager.setCurrentItem(1); } else if (hiActivities.size() == 1) { mViewPager.setCurrentItem(0); } else if (hiActivities.size() == 2) { mViewPager.setCurrentItem(1); } HiActivity currentSelectedHiActivity = mHiActivityAdapter.getItem(mViewPager.getCurrentItem()); mCurrentSelectedHiActivityNameTextView.setText(currentSelectedHiActivity.getName()); } } if (TAG_API_GET_ACTIVITY_END.equals(tag)) { JSONObject jsonObject = JsonUtil.getJSONObject(response.getJsonStr()); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setDateFormat("yyyy-MM-dd hh:mm:ss"); Gson gson = gsonBuilder.create(); Type listType = new TypeToken<List<HiActivity>>() {}.getType(); List<HiActivity> hiActivities = gson.fromJson(JsonUtil.getJSONArray(jsonObject, "list").toString(), listType); if (hiActivities != null) { mHiActivityListAdapter.addAll(hiActivities); mHiActivityListAdapter.notifyDataSetChanged(); } } }
@Override public String asJsonString() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Model.class, new JsonModelAdapter()); Gson gson = builder.create(); return gson.toJson(this, modelType); }
public static String toJson( Object target, Type targetType, boolean isSerializeNulls, Double version, String datePattern, boolean excludesFieldsWithoutExpose) { if (target == null) return EMPTY_JSON; GsonBuilder builder = new GsonBuilder(); if (isSerializeNulls) builder.serializeNulls(); if (version != null) builder.setVersion(version.doubleValue()); if (TextUtils.isEmpty(datePattern)) datePattern = DEFAULT_DATE_PATTERN; builder.setDateFormat(datePattern); if (excludesFieldsWithoutExpose) builder.excludeFieldsWithoutExposeAnnotation(); String result = EMPTY; Gson gson = builder.create(); try { if (targetType != null) { result = gson.toJson(target, targetType); } else { result = gson.toJson(target); } } catch (Exception ex) { if (target instanceof Collection || target instanceof Iterator || target instanceof Enumeration || target.getClass().isArray()) { result = EMPTY_JSON_ARRAY; } else result = EMPTY_JSON; } return result; }
protected String generateRequestBody() { final GsonBuilder builder = new GsonBuilder(); final Gson gson = builder.create(); Map<String, Boolean> deployMap = new HashMap<String, Boolean>(); deployMap.put("enabled", enabled); return gson.toJson(deployMap); }
public ConnectorStore() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(UpdateInfo.class, new UpdateInfoSerializer()); gson = gsonBuilder.create(); mapper.setVisibility(JsonMethod.FIELD, JsonAutoDetect.Visibility.ANY); mapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false); }
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); } }
/** * Convenience method for returning a Gson object with a registered GSon TypeAdaptor i.e. custom * deserializer. * * @return A Gson object that can be used to convert Json into a {@link Event}. */ public static Gson getGsonBuilder(Context context) { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter( new TypeToken<Map<Event, Collection<Team>>>() {}.getType(), new EventsDeserializer(context)); return gsonBuilder.create(); }
// TODO - get the GsonBuilder working for us. Much better than using our own code public static String WrapAndStringify(ResultBase result) { RawSubmitResultContainer toSubmit = new RawSubmitResultContainer(); toSubmit.jsonResult = RawStringify(result); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); return gson.toJson(toSubmit); }
public static Gson create() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(DateTime.class, new DateTimeDeserializer()); gsonBuilder.registerTypeAdapter(RestResponse.class, new UserRestResponseConverter()); // gsonBuilder.registerTypeAdapter(User.class, new UserGsonConverter()); return gsonBuilder.create(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.creat_ad); SharedPreferences sharedPreferences = getSharedPreferences(SignUp.SAVE_TEXT, 0); String save = sharedPreferences.getString("user", null); editTextName = (EditText) findViewById(R.id.editTextNameB); editTextDateStart = (EditText) findViewById(R.id.editTextDateStart); editTextDateEnd = (EditText) findViewById(R.id.editTextDateEnd); editTextCityStart = (EditText) findViewById(R.id.editTextCityStart); editTextCityEnd = (EditText) findViewById(R.id.editTextCityEnd); editTextAbout = (EditText) findViewById(R.id.editTextAbout); editTextPrice = (EditText) findViewById(R.id.editTextPrice); editTextCountSits = (EditText) findViewById(R.id.editTextCountSits); editTextDateStart = (EditText) findViewById(R.id.editTextDateStart); editTextTimeStart = (EditText) findViewById(R.id.editTextTimeStart); editTextTimeEnd = (EditText) findViewById(R.id.editTextTimeEnd); editTextCurrency = (EditText) findViewById(R.id.editTextCurrency); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); user = gson.fromJson(save, User.class); }
/** * Execute the Request for myLocation * * @param _url * @return Return the Search Response * @throws Exception */ private SearchMyLocationResponse requestSearchMyLocation(String _url) throws Exception { SearchMyLocationResponse sResponse = null; final HttpClient client = new DefaultHttpClient(); final HttpGet request = new HttpGet(_url); request.setHeader("Accept", "application/json"); Log.i(logTag, "Executing requestSearchMyLocation"); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream stream = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } stream.close(); String responseString = sb.toString(); GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); JSONObject json = new JSONObject(responseString); sResponse = gson.fromJson(json.toString(), SearchMyLocationResponse.class); } /* Return */ Log.i(logTag, "Finish request my_location"); return sResponse; }
public void onClickCreat(View view) { CurrencyAd ad = new CurrencyAd( editTextName.getText().toString(), editTextCurrency.getText().toString(), editTextCountSits.getText().toString(), null, editTextPrice.getText().toString(), user.getEmail(), editTextAbout.getText().toString(), editTextCityEnd.getText().toString(), editTextCityStart.getText().toString(), editTextDateEnd.getText().toString(), editTextDateStart.getText().toString(), editTextTimeEnd.getText().toString(), editTextTimeStart.getText().toString()); GsonBuilder builder1 = new GsonBuilder(); Gson gson1 = builder1.create(); String a = gson1.toJson(ad); try { sent = new CreatAdAsyncTask().execute(gson1.toJson(ad)).get(5, TimeUnit.SECONDS); startActivity(new Intent(this, MainActivity.class)); Toast.makeText(this, "Ваша заявка создана!", Toast.LENGTH_LONG).show(); } catch (InterruptedException e) { Logger.getAnonymousLogger().warning(e.getMessage()); } catch (ExecutionException e) { Logger.getAnonymousLogger().warning(e.getMessage()); } catch (TimeoutException e) { Toast.makeText(this, "Oooops!", Toast.LENGTH_SHORT).show(); } }
private MetricBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(CustomAggregator.class, new CustomAggregatorSerializer()); builder.registerTypeAdapter(CustomGrouper.class, new CustomGrouperSerializer()); builder.registerTypeAdapter(DataPoint.class, new DataPointSerializer()); mapper = builder.create(); }
@Override public String encode(Student student) throws EncodeException { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); System.out.println("JSONEncoder....encode.." + gson.toJson(student)); return gson.toJson(student); }
private static Gson createGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Category.class, new CategoryDeserializer()); gsonBuilder.registerTypeAdapter(Question.class, new QuestionDeserializer()); gsonBuilder.registerTypeAdapter(Choice.class, new ChoiceDeserializer()); return gsonBuilder.create(); }
@Override public boolean parse( @NonNull String line, @NonNull OutputLineReader reader, @NonNull List<Message> messages, @NonNull ILogger logger) throws ParsingFailedException { Matcher m = MSG_PATTERN.matcher(line); if (!m.matches()) { return false; } String json = m.group(1); if (json.trim().isEmpty()) { return false; } GsonBuilder gsonBuilder = new GsonBuilder(); MessageJsonSerializer.registerTypeAdapters(gsonBuilder); Gson gson = gsonBuilder.create(); try { Message msg = gson.fromJson(json, Message.class); messages.add(msg); return true; } catch (JsonParseException e) { throw new ParsingFailedException(e); } }
static { GsonBuilder var0 = new GsonBuilder(); var0.registerTypeHierarchyAdapter(IChatComponent.class, new IChatComponent.Serializer()); var0.registerTypeHierarchyAdapter(ChatStyle.class, new ChatStyle.Serializer()); var0.registerTypeAdapterFactory(new EnumTypeAdapterFactory()); GSON = var0.create(); }
private OkHttpClientManager() { mOkHttpClient = new OkHttpClient(); // cookie enabled mOkHttpClient.setCookieHandler(new CookieManager(null, CookiePolicy.ACCEPT_ORIGINAL_SERVER)); mDelivery = new Handler(Looper.getMainLooper()); final int sdk = Build.VERSION.SDK_INT; if (sdk >= 23) { GsonBuilder gsonBuilder = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC); mGson = gsonBuilder.create(); } else { mGson = new Gson(); } // just for test if (false) { mOkHttpClient.setHostnameVerifier( new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } }
private void initRequestHelpers() { queue = Volley.newRequestQueue(this); GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Game.class, new TwitchResultItemParser()); gson = builder.create(); }
/** * Converts the properties object into a JSON string. * * @param properties The properties object to convert. * @param envelope Envelope for resulting JSON object. Null if not needed. * @return A JSON string representing the object. */ public static String toJson(PropertiesConfiguration properties, String envelope) { JsonObject json = new JsonObject(); Iterator<String> i = properties.getKeys(); while (i.hasNext()) { final String key = i.next(); final String value = properties.getString(key); if (value.equals("true") || value.equals("false")) { json.addProperty(key.toString(), Boolean.parseBoolean(value)); } else if (PATTERN_INTEGER.matcher(value).matches()) { json.addProperty(key.toString(), Integer.parseInt(value)); } else if (PATTERN_FLOAT.matcher(value).matches()) { json.addProperty(key.toString(), Float.parseFloat(value)); } else { json.addProperty(key.toString(), value); } } GsonBuilder gsonBuilder = new GsonBuilder().disableHtmlEscaping(); Gson gson = gsonBuilder.create(); String _json = gson.toJson(json); if (envelope != null && !envelope.isEmpty()) { _json = envelope(_json, envelope); } return _json; }
@Provides @Singleton Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); }
/** * Writes configuration. * * @param name name * @param writeType write type * @throws IOException when write fails */ public static void writeAbilityConfig(String name, Ability config, WriteReadType writeType) throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Ability.class, new AbilityDeserializer()); Gson gson = gsonBuilder.create(); writeConfig(gson.toJson(config), writeType, name + IOConstants.FILE_EXTENTENSION); }
public MainSQL(Ticketer instance) { this.TI = instance; gsonBuilder = new GsonBuilder() .disableHtmlEscaping() .excludeFieldsWithModifiers(Modifier.VOLATILE, Modifier.TRANSIENT); gson = gsonBuilder.create(); }
/** * Create a new instance of Gson and tack on all our custom deserializers * * @return a Gson instance */ public static Gson getGsonInstance() { if (gson == null) { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(Event.class, new EventDeserializer()); gson = builder.create(); } return gson; }
/** * Writes configuration. * * @param writeType write type * @throws IOException when write fails */ public static void writeProfessionConfig(ProfessionConfiguration config, WriteReadType writeType) throws IOException { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Ability.class, new AbilityDeserializer()); Gson gson = gsonBuilder.create(); writeConfig(gson.toJson(config), writeType, ConfigType.PROFESSION.getFileName()); }
@GET public Response getAllJarsInfo() { List<JarInfo> jarInfo = getJarInfo(); GsonBuilder gsonBuilder = new GsonBuilder().serializeNulls(); Gson gson = gsonBuilder.create(); String propsJson = gson.toJson(new KaryonAdminResponse(jarInfo)); return Response.ok(propsJson).build(); }
/** @param args */ public static void main(String[] args) { AssignedLabel al = new AssignedLabel("foo", "bar", "baz"); System.out.println(al); String json = al.toString(); GsonBuilder builder = new GsonBuilder(); Type type = new TypeToken<AssignedLabel>() {}.getType(); Type ctype = new TypeToken<CorrectLabel>() {}.getType(); Type atype = new TypeToken<Collection<AssignedLabel>>() {}.getType(); Type cattype = new TypeToken<Category>() {}.getType(); Type catstype = new TypeToken<Collection<Category>>() {}.getType(); Type mattype = new TypeToken<MultinomialConfusionMatrix>() {}.getType(); builder.registerTypeAdapter(type, AssignedLabel.deserializer); builder.registerTypeAdapter(ctype, CorrectLabel.deserializer); builder.registerTypeAdapter(cattype, Category.deserializer); builder.registerTypeAdapter(mattype, MultinomialConfusionMatrix.deserializer); Gson gson = builder.create(); System.out.println(gson.fromJson(json, type)); System.out.println(gson.fromJson(json, type).getClass()); CorrectLabel cl = new CorrectLabel("foo", "bar"); System.out.println(cl); String t = cl.toString(); System.out.println(gson.fromJson(t, ctype)); System.out.println(gson.fromJson(t, ctype).getClass()); Collection<AssignedLabel> col = new HashSet<AssignedLabel>(); for (int i = 0; i < 10; i++) { String foo = i + ""; col.add(new AssignedLabel(foo, foo, foo)); } String tmp = gson.toJson(col); System.out.println(gson.fromJson(tmp, atype).getClass()); Collection<Category> cats = new HashSet<Category>(); for (int i = 0; i < 5; i++) { cats.add(new Category("" + i)); } System.out.println(gson.toJson(cats)); String foo = gson.toJson(cats); System.out.println(gson.fromJson(foo, catstype).getClass()); Datum datum = new Datum("foo", new HashSet<Category>(cats)); System.out.println(datum); Worker worker = new Worker("foo", new HashSet<Category>(cats)); System.out.println(worker); ConfusionMatrix mat = new MultinomialConfusionMatrix(cats); String matrix = gson.toJson(mat); System.out.println(matrix); ConfusionMatrix mat2 = gson.fromJson(matrix, mattype); System.out.println(mat2.getClass()); }
/** * Returns string values for all the counters stored * * @return string values for all the counters stored */ @GET @Produces(MediaType.APPLICATION_JSON) public Response getAllCounters() { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); String json = gson.toJson(Counters.getCounterBeans()); return Response.ok(json, MediaType.APPLICATION_JSON).build(); }