本文整理了Java中com.google.gson.Gson
类的一些代码示例,展示了Gson
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Gson
类的具体详情如下:
包路径:com.google.gson.Gson
类名称:Gson
[英]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.
[中]这是使用Gson的主要类。Gson的使用通常是先构造一个Gson实例,然后在其上调用#toJson(Object)或#fromJson(String,Class)方法。Gson实例是线程安全的,因此您可以跨多个线程自由地重用它们。
如果您只需要默认配置,则可以通过调用new Gson()创建一个Gson实例。您还可以使用GsonBuilder构建具有各种配置选项的Gson实例,如版本控制支持、漂亮打印、自定义JSONSerializer、JSONDeserializer和InstanceCreators。
下面是如何将Gson用于简单类的示例:
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
如果正在序列化/反序列化的对象是ParameterizedType(即,至少包含一个类型参数,并且可能是数组),则必须使用#toJson(对象,类型)或#fromJson(字符串,类型)方法。以下是序列化和反序列化参数化类型的示例:
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);
有关更完整的示例集,请参见{$0$}。
代码示例来源: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;
}
内容来源于网络,如有侵权,请联系作者删除!