读书人

Gson 应用例子

发布时间: 2012-09-29 10:30:01 作者: rapoo

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:?

    Store shared state in static fieldsDeclare the serializer/deserializer as inner classes of a parent type, and use the instance fields of parent type to store shared stateUse Java ThreadLocal
1 and 2 are not thread-safe options, but 3 is.?
StreamingIn addition Gson's object model and data binding, you can use Gson to read from and write to a?stream. You can also combine streaming and object model access to get the best of both approaches.Issues in Designing GsonSee the?Gson design document?for a discussion of issues we faced while designing Gson. It also include a comparison of Gson with other Java libraries that can be used for Json conversion.
Future Enhancements to GsonFor the latest list of proposed enhancements or if you'd like to suggest new ones, see the?Issues section?under the project website.

?

读书人网 >开源软件

热点推荐