Gson 使用例子
这个网页通过正常的手段是访问不到的, 为了大家能够方便的学习Gson。 因此将原文应用到此。
OverviewGson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson is an open-source project hosted atId<T> type that has same serialization for all generic types
import java.lang.reflect.Modifier;
Gson gson = new GsonBuilder()
??? .excludeFieldsWithModifier(Modifier.STATIC)
??? .create();
NOTE: you can use any number of theGson gson = new GsonBuilder()
??? .excludeFieldsWithModifier(Modifier.STATIC, Modifier.TRANSIENT, Modifier.VOLATILE)
??? .create();
Gson's @Expose
This feature provides a way where you can mark certain fields of your objects to be excluded for consideration for serialization and deserialization to JSON. To use this annotation, you must create Gson by using
? @Retention(RetentionPolicy.RUNTIME)
? @Target({ElementType.FIELD})
? public @interface Foo {
??? // Field tag only annotation
? }
?
The following is an example of how to use both Gson naming policy features:
private class SomeObject {
? @SerializedName("custom_naming") private final String someField;
? private final String someOtherField;
? public SomeObject(String a, String b) {
??? this.someField = a;
??? this.someOtherField = b;
? }
}
SomeObject someObject = new SomeObject("first", "second");
Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE).create();
String jsonRepresentation = gson.toJson(someObject);
System.out.println(jsonRepresentation);
======== OUTPUT ========
{"custom_naming":"first","SomeOtherField":"second"}
If you have a need for custom naming policy (see this discussion), you can use the?@SerializedName?annotation.?
Sharing State Across Custom Serializers and DeserializersSometimes you need to share state across custom serializers/deserializers (see this discussion). You can use the following three strategies to accomplish this:?
?