Tabnine Logo
Gson
Code IndexAdd Tabnine to your IDE (free)

How to use
Gson
in
com.google.gson

Best Java code snippets using com.google.gson.Gson (Showing top 20 results out of 25,119)

Refine searchRefine arrow

  • GsonBuilder
  • JsonObject
  • JsonElement
  • JsonParser
  • JsonArray
  • InputStreamReader
origin: skylot/jadx

  private static <T> T get(String url, Type type) throws IOException {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    if (con.getResponseCode() == 200) {
      Reader reader = new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8);
      return GSON.fromJson(reader, type);
    }
    return null;
  }
}
origin: ata4/disunity

@Override
public void print(Collection<TableModel> models) {
  Gson gson = new GsonBuilder().setPrettyPrinting().create();
  JsonObject jsonRoot = new JsonObject();
  if (file != null) {
    jsonRoot.add("file", new JsonPrimitive(file.toString()));
  }
  models.forEach(model -> {
    jsonRoot.add(model.name().toLowerCase(), tableToJson(model.table(), gson));
  });
  gson.toJson(jsonRoot, out);
}
origin: aa112901/remusic

@Override
protected Void doInBackground(Void... params) {
  gson = new Gson();
  JsonObject result = HttpUtil.getResposeJsonObject(BMA.GeDan.geDan(1, 10));
  if (result == null) {
    return null;
  }
  //热门歌单
  JsonArray pArray = result.get("content").getAsJsonArray();
  if (pArray == null) {
    return null;
  }
  int plen = pArray.size();
  for (int i = 0; i < plen; i++) {
    GedanInfo GedanInfo = gson.fromJson(pArray.get(i), GedanInfo.class);
    recommendList.add(GedanInfo);
  }
  return null;
}
origin: apache/incubator-dubbo

/**
 * Describe a Java interface in Json schema.
 *
 * @return Service description
 */
public static String schema(final Class<?> clazz) {
  ServiceDefinition sd = build(clazz);
  Gson gson = new Gson();
  return gson.toJson(sd);
}
origin: ctripcorp/apollo

private String mockLongPollBody(String notificationsStr) {
 List<ApolloConfigNotification> oldNotifications = gson.fromJson(notificationsStr, notificationType);
 List<ApolloConfigNotification> newNotifications = new ArrayList<>();
 for (ApolloConfigNotification notification : oldNotifications) {
  newNotifications
    .add(new ApolloConfigNotification(notification.getNamespaceName(), notification.getNotificationId() + 1));
 }
 return gson.toJson(newNotifications);
}
origin: apache/incubator-gobblin

public static List<ProducerJob> deserialize(String jobs) {
 if (jobs == null || jobs.trim().isEmpty()) {
  jobs = "[]";
 }
 JsonArray jobsJson = new JsonParser().parse(jobs).getAsJsonArray();
 return new Gson().fromJson(jobsJson, new TypeToken<ArrayList<SimpleProducerJob>>() {
 }.getType());
}
origin: Impetus/Kundera

Reader reader = new InputStreamReader(content);
JsonObject json = gson.fromJson(reader, JsonObject.class);
JsonElement jsonElement = json.get("rows");
JsonArray array = jsonElement.getAsJsonArray();
for (JsonElement element : array)
  JsonElement value = element.getAsJsonObject().get("value").getAsJsonObject().get(inverseJoinColumnName);
  if (value != null)
origin: redwarp/9-Patch-Resizer

public void load(String path) {
 try {
  Gson gson = new Gson();
  JsonParser parser = new JsonParser();
  InputStream preferenceStream;
  try {
    parser.parse(new InputStreamReader(preferenceStream)).getAsJsonObject();
  JsonArray densitiesArray = densitiesObject.get(KEY_DENSITIES).getAsJsonArray();
  list = gson.fromJson(densitiesArray, listType);
  String defaultDensityName = densitiesObject.get(KEY_SOURCE).getAsString();
  for (ScreenDensity density : list) {
   if (density.getName().equals(defaultDensityName)) {
  JsonElement keepSameDensityElement = densitiesObject.get(
    KEY_KEEP_SAME_DENSITY_FILE);
  if (keepSameDensityElement != null) {
origin: apache/incubator-gobblin

private JsonObject initResources(String resourceFilePath) {
 Type listType = new TypeToken<JsonObject>() {
 }.getType();
 Gson gson = new Gson();
 JsonObject testData =
   gson.fromJson(new InputStreamReader(this.getClass().getResourceAsStream(resourceFilePath)), listType);
 jsonRecord = testData.get("record").getAsJsonObject();
 jsonSchema = testData.get("schema").getAsJsonArray();
 WorkUnit workUnit = new WorkUnit(new SourceState(),
   new Extract(new SourceState(), Extract.TableType.SNAPSHOT_ONLY, "namespace", "dummy_table"));
 state = new WorkUnitState(workUnit);
 state.setProp(ConfigurationKeys.CONVERTER_AVRO_TIME_FORMAT, "HH:mm:ss");
 state.setProp(ConfigurationKeys.CONVERTER_AVRO_DATE_TIMEZONE, "PST");
 return testData;
}
origin: Impetus/Kundera

    kunderaMetadata);
String _id = object.get("_id").getAsString();
    Reader reader = new InputStreamReader(content);
    JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
    JsonElement rev = jsonObject.get("_rev");
    object.add("_rev", rev);
origin: SpigotMC/BungeeCord

public JsonProvider(String resourcePath) throws IOException
{
  try ( InputStreamReader rd = new InputStreamReader( JsonProvider.class.getResourceAsStream( resourcePath ), Charsets.UTF_8 ) )
  {
    JsonObject obj = new Gson().fromJson( rd, JsonObject.class );
    for ( Map.Entry<String, JsonElement> entries : obj.entrySet() )
    {
      translations.put( entries.getKey(), entries.getValue().getAsString() );
    }
  }
}
origin: apache/incubator-gobblin

@BeforeClass
public static void setUp() {
 Type listType = new TypeToken<JsonObject>() {
 }.getType();
 Gson gson = new Gson();
 JsonObject testData = gson.fromJson(
   new InputStreamReader(JsonIntermediateToParquetGroupConverter.class.getResourceAsStream(RESOURCE_PATH)), listType);
 testCases = testData.getAsJsonObject();
 SourceState source = new SourceState();
 workUnit = new WorkUnitState(
   source.createWorkUnit(source.createExtract(Extract.TableType.SNAPSHOT_ONLY, "test_namespace", "test_table")));
}
origin: apache/incubator-gobblin

   new BufferedReader(new InputStreamReader(response.getEntity().getContent(),
                        ConfigurationKeys.DEFAULT_CHARSET_ENCODING)));
 String line;
 return new JsonObject();
JsonElement jsonElement = GSON.fromJson(sb.toString(), JsonElement.class);
return jsonElement;
origin: Impetus/Kundera

  key = ((JsonElement) key).getAsString();
Reader reader = new InputStreamReader(content);
JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
if (jsonObject.get(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName()) == null)
origin: Impetus/Kundera

/**
 * Gets the json from response.
 * 
 * @param response
 *            the response
 * @return the json from response
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
private JsonArray getJsonFromResponse(HttpResponse response) throws IOException
{
  InputStream content = response.getEntity().getContent();
  Reader reader = new InputStreamReader(content);
  JsonObject json = gson.fromJson(reader, JsonObject.class);
  JsonElement jsonElement = json.get("rows");
  return jsonElement == null ? null : jsonElement.getAsJsonArray();
}
origin: chanjarster/weixin-java-tools

@Override
public List<WxCpTag> tagGet() throws WxErrorException {
 String url = "https://qyapi.weixin.qq.com/cgi-bin/tag/list";
 String responseContent = get(url, null);
 JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
 return WxCpGsonBuilder.INSTANCE.create()
   .fromJson(
     tmpJsonElement.getAsJsonObject().get("taglist"),
     new TypeToken<List<WxCpTag>>() {
     }.getType()
   );
}
origin: iSoron/uhabits

@NonNull
public Command parse(@NonNull String json)
    .fromJson(json, ArchiveHabitsCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, ChangeHabitColorCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, CreateHabitCommand.Record.class)
    .toCommand(modelFactory, habitList);
    .fromJson(json, CreateRepetitionCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, DeleteHabitsCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, EditHabitCommand.Record.class)
    .toCommand(modelFactory, habitList);
    .fromJson(json, ToggleRepetitionCommand.Record.class)
    .toCommand(habitList);
    .fromJson(json, UnarchiveHabitsCommand.Record.class)
    .toCommand(habitList);
origin: chanjarster/weixin-java-tools

@Override
public List<WxMpUserSummary> getUserSummary(Date beginDate, Date endDate) throws WxErrorException {
 String url = "https://api.weixin.qq.com/datacube/getusersummary";
 JsonObject param = new JsonObject();
 param.addProperty("begin_date", SIMPLE_DATE_FORMAT.format(beginDate));
 param.addProperty("end_date", SIMPLE_DATE_FORMAT.format(endDate));
 String responseContent = post(url, param.toString());
 JsonElement tmpJsonElement = Streams.parse(new JsonReader(new StringReader(responseContent)));
 return WxMpGsonBuilder.INSTANCE.create().fromJson(tmpJsonElement.getAsJsonObject().get("list"),
   new TypeToken<List<WxMpUserSummary>>() {
   }.getType());
}
origin: gocd/gocd

private Map<String, Object> getMetadataFromFile(String artifactId) throws IOException {
  final String fileToString = FileUtils.readFileToString(metadataFileDest, StandardCharsets.UTF_8);
  LOGGER.debug(format("Reading metadata from file %s.", metadataFileDest.getAbsolutePath()));
  final Type type = new TypeToken<Map<String, Object>>() {
  }.getType();
  final Map<String, Map> allArtifactsPerPlugin = new GsonBuilder().create().fromJson(fileToString, type);
  return allArtifactsPerPlugin.get(artifactId);
}
origin: aa112901/remusic

public static MusicDetailInfo getInfo(final String id) {
  MusicDetailInfo info = null;
  try {
    JsonObject jsonObject = HttpUtil.getResposeJsonObject(BMA.Song.songBaseInfo(id).trim()).get("result")
        .getAsJsonObject().get("items").getAsJsonArray().get(0).getAsJsonObject();
    info = MainApplication.gsonInstance().fromJson(jsonObject, MusicDetailInfo.class);
  } catch (Exception e) {
    e.printStackTrace();
  }
  return info;
}
com.google.gsonGson

Javadoc

This is the main class for using Gson. Gson is typically used by first constructing a Gson instance and then invoking #toJson(Object) or #fromJson(String,Class)methods on it. Gson instances are Thread-safe so you can reuse them freely across multiple threads.

You can create a Gson instance by invoking new Gson() if the default configuration is all you need. You can also use GsonBuilder to build a Gson instance with various configuration options such as versioning support, pretty printing, custom JsonSerializers, JsonDeserializers, and InstanceCreators.

Here is an example of how Gson is used for a simple Class:

 
Gson gson = new Gson(); // Or use new GsonBuilder().create(); 
MyType target = new MyType(); 
String json = gson.toJson(target); // serializes target to Json 
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2 

If the object that your are serializing/deserializing is a ParameterizedType(i.e. contains at least one type parameter and may be an array) then you must use the #toJson(Object,Type) or #fromJson(String,Type) method. Here is an example for serializing and deserialing a ParameterizedType:

 
Type listType = new TypeToken<List<String>>() {}.getType(); 
List<String> target = new LinkedList<String>(); 
target.add("blah"); 
Gson gson = new Gson(); 
String json = gson.toJson(target, listType); 
List<String> target2 = gson.fromJson(json, listType); 

See the Gson User Guide for a more complete set of examples.

Most used methods

  • fromJson
    This method deserializes the specified Json into an object of the specified type. This method is use
  • toJson
    This method serializes the specified object, including those of generic types, into its equivalent J
  • <init>
  • toJsonTree
    This method serializes the specified object, including those of generic types, into its equivalent r
  • getAdapter
    Returns the type adapter for type.
  • getDelegateAdapter
    This method is used to get an alternate type adapter for the specified type. This is used to access
  • newJsonWriter
    Returns a new JSON writer configured for this GSON and with the non-execute prefix if that is config
  • newJsonReader
    Returns a new JSON reader configured for the settings on this Gson instance.
  • assertFullConsumption
  • doubleAdapter
  • floatAdapter
  • longAdapter
  • floatAdapter,
  • longAdapter,
  • fieldNamingStrategy,
  • toString,
  • atomicLongAdapter,
  • atomicLongArrayAdapter,
  • checkValidFloatingPoint,
  • excluder,
  • newBuilder,
  • fromGson

Popular in Java

  • Reactive rest calls using spring rest template
  • findViewById (Activity)
  • scheduleAtFixedRate (Timer)
  • requestLocationUpdates (LocationManager)
  • FileInputStream (java.io)
    An input stream that reads bytes from a file. File file = ...finally if (in != null) in.clos
  • Thread (java.lang)
    A thread is a thread of execution in a program. The Java Virtual Machine allows an application to ha
  • ServerSocket (java.net)
    This class represents a server-side socket that waits for incoming client connections. A ServerSocke
  • SimpleDateFormat (java.text)
    Formats and parses dates in a locale-sensitive manner. Formatting turns a Date into a String, and pa
  • Logger (org.apache.log4j)
    This is the central class in the log4j package. Most logging operations, except configuration, are d
  • Scheduler (org.quartz)
    This is the main interface of a Quartz Scheduler. A Scheduler maintains a registry of org.quartz.Job
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now