private static <T> void populate(GsonBuilder builder, String json, Class<T> type, final T into) { builder.registerTypeAdapter(type, (InstanceCreator<T>) t -> into) .create() .fromJson(json, type); } }
/** * Construct a new {@code GsonHttpMessageConverter} with default configuration. */ public GsonHttpMessageConverter() { this.gson = new Gson(); }
Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonParser jp = new JsonParser(); JsonElement je = jp.parse(uglyJSONString); String prettyJsonString = gson.toJson(je);
public String parse(String jsonLine) { JsonElement jelement = new JsonParser().parse(jsonLine); JsonObject jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("data"); JsonArray jarray = jobject.getAsJsonArray("translations"); jobject = jarray.get(0).getAsJsonObject(); String result = jobject.get("translatedText").toString(); return result; }
public static JadxSettings fromString(String jsonSettings) { return GSON.fromJson(jsonSettings, JadxSettings.class); }
public static String makeString(JadxSettings settings) { return GSON.toJson(settings); }
/** * Obtain a {@link GsonBuilder} which Base64-encodes {@code byte[]} * properties when reading and writing JSON. * <p>A custom {@link com.google.gson.TypeAdapter} will be registered via * {@link GsonBuilder#registerTypeHierarchyAdapter(Class, Object)} which * serializes a {@code byte[]} property to and from a Base64-encoded String * instead of a JSON array. */ public static GsonBuilder gsonBuilderWithBase64EncodedByteArrays() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeHierarchyAdapter(byte[].class, new Base64TypeAdapter()); return builder; }
@Override public byte[] deserialize(JsonElement json, Type type, JsonDeserializationContext cxt) { return Base64Utils.decodeFromString(json.getAsString()); } }
@Override public T convert(ResponseBody value) throws IOException { JsonReader jsonReader = gson.newJsonReader(value.charStream()); try { T result = adapter.read(jsonReader); if (jsonReader.peek() != JsonToken.END_DOCUMENT) { throw new JsonIOException("JSON document was not fully consumed."); } return result; } finally { value.close(); } } }
@Override public T apply(String input) { return gson.fromJson(input, responseType); } };
public static String batchTransformToJSON(Set<GrayReleaseRuleItemDTO> ruleItems) { return gson.toJson(ruleItems); } }
Type listType = new TypeToken<ArrayList<YourClass>>(){}.getType(); List<YourClass> yourClassList = new Gson().fromJson(jsonArray, listType);
@Override public T apply(String input) { return gson.fromJson(input, responseType); } };
/** * Create an instance using a default {@link Gson} instance for conversion. Encoding to JSON and * decoding from JSON (when no charset is specified by a header) will use UTF-8. */ public static GsonConverterFactory create() { return create(new Gson()); }