- 浏览: 27161 次
- 性别:
- 来自: 深圳
文章分类
最新评论
1.简单的处理 list 和 map
Java 代码
1. Gson gson = new Gson();
2. List testList = new ArrayList();
3. testList.add("first");
4. testList.add("second");
5. String listToJson = gson.toJson(testList);
6. System.out.println(listToJson);
7. //prints ["first","second"]
8.
9. Map testMap = new HashMap();
10. testMap.put("id", "id.first");
11. testMap.put("name","name.second");
12. String mapToJson = gson.toJson(testMap);
13. System.out.println(mapToJson);
14. //prints {"id":"id.first","name":"name.second"}
Gson gson = new Gson();
List testList = new ArrayList();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
System.out.println(listToJson);
//prints ["first","second"]
Map testMap = new HashMap();
testMap.put("id", "id.first");
testMap.put("name","name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson);
//prints {"id":"id.first","name":"name.second"}
2.处理带泛型的集合
Java 代码
1. List<TestBean> testBeanList = new ArrayList<TestBean>();
2. TestBean testBean = new TestBean();
3. testBean.setId("id");
4. testBean.setName("name");
5. testBeanList.add(testBean);
List<TestBean> testBeanList = new ArrayList<TestBean>();
TestBean testBean = new TestBean();
testBean.setId("id");
testBean.setName("name");
testBeanList.add(testBean);
Java 代码
1. java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<T
estBean>>() {
2. }.getType();
3. String beanListToJson = gson.toJson(testBeanList,type);
4. System.out.println(beanListToJson);
5. //prints [{"id":"id","name":"name"}]
6.
7. List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
8. System.out.println(testBeanListFromJson);
9. //prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]
java.lang.reflect.Type type = new
com.google.gson.reflect.TypeToken<List<TestBean>>() {
}.getType();
String beanListToJson = gson.toJson(testBeanList,type);
System.out.println(beanListToJson);
//prints [{"id":"id","name":"name"}]
List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]
map 等其他集合类型同上
3.Date 类型转化
先写工具类
Java 代码
1. import java.lang.reflect.Type;
2.
3. import com.google.gson.JsonDeserializationContext;
4. import com.google.gson.JsonDeserializer;
5. import com.google.gson.JsonElement;
6. import com.google.gson.JsonParseException;
7.
8. public class UtilDateDeserializer implements JsonDeserializer<java.util.Da
te> {
9.
10. @Override
11. public java.util.Date deserialize(JsonElement json, Type typeOfT, Jso
nDeserializationContext context)
12. throws JsonParseException {
13. return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
14. }
15. }
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class UtilDateDeserializer implements JsonDeserializer<java.util.Date> {
@Override
public java.util.Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
}
}
Java 代码
1. import java.lang.reflect.Type;
2.
3. import com.google.gson.JsonElement;
4. import com.google.gson.JsonPrimitive;
5. import com.google.gson.JsonSerializationContext;
6. import com.google.gson.JsonSerializer;
7.
8. public class UtilDateSerializer implements JsonSerializer<java.util.Date>
{
9.
10. @Override
11. public JsonElement serialize(java.util.Date src, Type typeOfSrc,
12. JsonSerializationContext context) {
13. return new JsonPrimitive(src.getTime());
14. }
15.
16. }
import java.lang.reflect.Type;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class UtilDateSerializer implements JsonSerializer<java.util.Date> {
@Override
public JsonElement serialize(java.util.Date src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
}
Java 代码
1. /**
2. * 序列化方法
3. * @param bean
4. * @param type
5. * @return
6. */
7. public static String bean2json(Object bean, Type type) {
8. Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.c
lass, new UtilDateSerializer())
9. .setDateFormat(DateFormat.LONG).create();
10. return gson.toJson(bean);
11. }
12.
13. /**
14. * 反序列化方法
15. * @param json
16. * @param type
17. * @return
18. */
19. public static <T> T json2bean(String json, Type type) {
20. Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.
class, new UtilDateDeserializer())
21. .setDateFormat(DateFormat.LONG).create();
22. return gson.fromJson(json, type);
23. }
/**
* 序列化方法
* @param bean
* @param type
* @return
*/
public static String bean2json(Object bean, Type type) {
Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new
UtilDateSerializer())
.setDateFormat(DateFormat.LONG).create();
return gson.toJson(bean);
}
/**
* 反序列化方法
* @param json
* @param type
* @return
*/
public static <T> T json2bean(String json, Type type) {
Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new
UtilDateDeserializer())
.setDateFormat(DateFormat.LONG).create();
return gson.fromJson(json, type);
}
现在开始测试
Java 代码
1. List<TestBean> testBeanList = new ArrayList<TestBean>();
2. TestBean testBean = new TestBean();
3. testBean.setId("id");
4. testBean.setName("name");
5. testBean.setBirthday(new java.util.Date());
6. testBeanList.add(testBean);
7.
8. java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<T
estBean>>() {
9. }.getType();
10. String beanListToJson = bean2json(testBeanList, type);
11. System.out.println("beanListToJson:" + beanListToJson);
12. //prints [{"id":"id","name":"name","birthday":1256531559390}]
13.
14. List<TestBean> testBeanListFromJson = json2bean(beanListToJson, type);
15. System.out.println(testBeanListFromJson);
16. //prints [TestBean@77a7f9[id=id,name=name,birthday=Mon Oct 26 12:39:05 CS
T 2009]]
List<TestBean> testBeanList = new ArrayList<TestBean>();
TestBean testBean = new TestBean();
testBean.setId("id");
testBean.setName("name");
testBean.setBirthday(new java.util.Date());
testBeanList.add(testBean);
java.lang.reflect.Type type = new
com.google.gson.reflect.TypeToken<List<TestBean>>() {
}.getType();
String beanListToJson = bean2json(testBeanList, type);
System.out.println("beanListToJson:" + beanListToJson);
//prints [{"id":"id","name":"name","birthday":1256531559390}]
List<TestBean> testBeanListFromJson = json2bean(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@77a7f9[id=id,name=name,birthday=Mon Oct 26 12:39:05 CST 2009]]
后记:对于 java.sql.Date 的转化同上类似,写两个类用于其序列化和反序列化即可
SQLDateDeserializer implements JsonDeserializer<java.sql.Date>
SQLDateSerializer implements JsonSerializer<java.sql.Date>
GsonBuilder api :
com.google.gson
Class GsonBuilder
java.lang.Object
com.google.gson.GsonBuilder
public final class GsonBuilderextends Object
Use this builder to construct a Gson instance when you need to set configuration
options other than the default. For Gson with default configuration, it is
simpler to use new Gson(). GsonBuilder is best used by creating it, and then
invoking its various configuration methods, and finally calling create.
The following is an example shows how to use the GsonBuilder to construct a Gson
instance:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Id.class, new IdTypeAdapter())
.serializeNulls()
.setDateFormat(DateFormat.LONG)
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.setVersion(1.0)
.create();
NOTE: the order of invocation of configuration methods does not matter.
Author:
Inderjeet Singh, Joel Leitch
Constructor Summary
GsonBuilder()
Creates a GsonBuilder instance that can be used to build Gson with
various configuration settings.
Method Summary
Gson create()
Creates a Gson instance based on the current
configuration.
GsonBuilder excludeFieldsWithModifiers(int... modifiers)
Configures Gson to excludes all class fields that have
the specified modifiers.
GsonBuilder excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration
for serialization or deserialization that do not have the Expose
annotation.
GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
Configures Gson for custom serialization or
deserialization.
GsonBuilder serializeNulls()
Configure Gson to serialize null fields.
GsonBuilder setDateFormat(int style)
Configures Gson to to serialize Date objects according
to the style value provided.
GsonBuilder setDateFormat(int dateStyle, int timeStyle)
Configures Gson to to serialize Date objects according
to the style value provided.
GsonBuilder setDateFormat(String pattern)
Configures Gson to serialize Date objects according to
the pattern provided.
GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
Configures Gson to apply a specific naming policy to an
object's field during serialization and deserialization.
GsonBuilder setPrettyPrinting()
Configures Gson to output Json that fits in a page for
批注 [1]: ======== CONSTRUCTOR
SUMMARY ========
批注 [2]:
批注 [3]: ========== METHOD
SUMMARY ===========
批注 [4]:
pretty printing.
GsonBuilder setVersion(double ignoreVersionsAfter)
Configures Gson to enable versioning support.
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Constructor Detail
GsonBuilder
public GsonBuilder()
Creates a GsonBuilder instance that can be used to build Gson with various
configuration settings. GsonBuilder follows the builder pattern, and it is
typically used by first invoking various configuration methods to set
desired options, and finally calling create().
Method Detail
setVersion
public GsonBuilder setVersion(double ignoreVersionsAfter)
Configures Gson to enable versioning support.
Parameters:
ignoreVersionsAfter - any field or type marked with a version higher
than this value are ignored during serialization or deserialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
excludeFieldsWithModifiers
public GsonBuilder excludeFieldsWithModifiers(int... modifiers)
Configures Gson to excludes all class fields that have the specified
modifiers. By default, Gson will exclude all fields marked transient or
static. This method will override that behavior.
批注 [5]:
批注 [6]: ========= CONSTRUCTOR
DETAIL ========
批注 [7]:
批注 [8]:
批注 [9]: ============ METHOD
DETAIL ==========
批注 [10]:
批注 [11]:
批注 [12]:
Parameters:
modifiers - the field modifiers. You must use the modifiers specified
in the Modifier class. For example, Modifier.TRANSIENT,
Modifier.STATIC.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
excludeFieldsWithoutExposeAnnotation
public GsonBuilder excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration for serialization
or deserialization that do not have the Expose annotation.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
serializeNulls
public GsonBuilder serializeNulls()
Configure Gson to serialize null fields. By default, Gson omits all fields
that are null during serialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
setFieldNamingPolicy
public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
Configures Gson to apply a specific naming policy to an object's field
during serialization and deserialization.
Parameters:
namingConvention - the JSON field naming convention to use for
serialization and deserialization.
批注 [13]:
批注 [14]:
批注 [15]:
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
setPrettyPrinting
public GsonBuilder setPrettyPrinting()
Configures Gson to output Json that fits in a page for pretty printing.
This option only affects Json serialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
setDateFormat
public GsonBuilder setDateFormat(String pattern)
Configures Gson to serialize Date objects according to the pattern provided.
You can call this method or setDateFormat(int) multiple times, but only the
last invocation will be used to decide the serialization format.
Note that this pattern must abide by the convention provided by
SimpleDateFormat class. See the documentation in SimpleDateFormat for more
information on valid date and time patterns.
Parameters:
pattern - the pattern that dates will be serialized/deserialized
to/from
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
setDateFormat
public GsonBuilder setDateFormat(int style)
Configures Gson to to serialize Date objects according to the style value
provided. You can call this method or setDateFormat(String) multiple times,
批注 [16]:
批注 [17]:
批注 [18]:
but only the last invocation will be used to decide the serialization
format.
Note that this style value should be one of the predefined constants in the
DateFormat class. See the documentation in DateFormat for more information
on the valid style constants.
Parameters:
style - the predefined date style that date objects will be
serialized/deserialized to/from
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
setDateFormat
public GsonBuilder setDateFormat(int dateStyle,
int timeStyle)
Configures Gson to to serialize Date objects according to the style value
provided. You can call this method or setDateFormat(String) multiple times,
but only the last invocation will be used to decide the serialization
format.
Note that this style value should be one of the predefined constants in the
DateFormat class. See the documentation in DateFormat for more information
on the valid style constants.
Parameters:
dateStyle - the predefined date style that date objects will be
serialized/deserialized to/from
timeStyle - the predefined style for the time portion of the date
objects
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
registerTypeAdapter
public GsonBuilder registerTypeAdapter(Type type,
批注 [19]:
批注 [20]:
Object typeAdapter)
Configures Gson for custom serialization or deserialization. This method
combines the registration of an InstanceCreator, JsonSerializer, and a
JsonDeserializer. It is best used when a single object typeAdapter
implements all the required interfaces for custom serialization with Gson.
If an instance creator, serializer or deserializer was previously
registered for the specified type, it is overwritten.
Parameters:
type - the type definition for the type adapter being registered
typeAdapter - This object must implement at least one of the
InstanceCreator, JsonSerializer, and a JsonDeserializer interfaces.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
create
public Gson create()
Creates a Gson instance based on the current configuration. This method is
free of side-effects to this GsonBuilder instance and hence can be called
multiple times.
Returns:
an instance of Gson configured with the options currently set in this
builder
批注 [21]:
Java 代码
1. Gson gson = new Gson();
2. List testList = new ArrayList();
3. testList.add("first");
4. testList.add("second");
5. String listToJson = gson.toJson(testList);
6. System.out.println(listToJson);
7. //prints ["first","second"]
8.
9. Map testMap = new HashMap();
10. testMap.put("id", "id.first");
11. testMap.put("name","name.second");
12. String mapToJson = gson.toJson(testMap);
13. System.out.println(mapToJson);
14. //prints {"id":"id.first","name":"name.second"}
Gson gson = new Gson();
List testList = new ArrayList();
testList.add("first");
testList.add("second");
String listToJson = gson.toJson(testList);
System.out.println(listToJson);
//prints ["first","second"]
Map testMap = new HashMap();
testMap.put("id", "id.first");
testMap.put("name","name.second");
String mapToJson = gson.toJson(testMap);
System.out.println(mapToJson);
//prints {"id":"id.first","name":"name.second"}
2.处理带泛型的集合
Java 代码
1. List<TestBean> testBeanList = new ArrayList<TestBean>();
2. TestBean testBean = new TestBean();
3. testBean.setId("id");
4. testBean.setName("name");
5. testBeanList.add(testBean);
List<TestBean> testBeanList = new ArrayList<TestBean>();
TestBean testBean = new TestBean();
testBean.setId("id");
testBean.setName("name");
testBeanList.add(testBean);
Java 代码
1. java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<T
estBean>>() {
2. }.getType();
3. String beanListToJson = gson.toJson(testBeanList,type);
4. System.out.println(beanListToJson);
5. //prints [{"id":"id","name":"name"}]
6.
7. List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
8. System.out.println(testBeanListFromJson);
9. //prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]
java.lang.reflect.Type type = new
com.google.gson.reflect.TypeToken<List<TestBean>>() {
}.getType();
String beanListToJson = gson.toJson(testBeanList,type);
System.out.println(beanListToJson);
//prints [{"id":"id","name":"name"}]
List<TestBean> testBeanListFromJson = gson.fromJson(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@1ea5671[id=id,name=name,birthday=<null>]]
map 等其他集合类型同上
3.Date 类型转化
先写工具类
Java 代码
1. import java.lang.reflect.Type;
2.
3. import com.google.gson.JsonDeserializationContext;
4. import com.google.gson.JsonDeserializer;
5. import com.google.gson.JsonElement;
6. import com.google.gson.JsonParseException;
7.
8. public class UtilDateDeserializer implements JsonDeserializer<java.util.Da
te> {
9.
10. @Override
11. public java.util.Date deserialize(JsonElement json, Type typeOfT, Jso
nDeserializationContext context)
12. throws JsonParseException {
13. return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
14. }
15. }
import java.lang.reflect.Type;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
public class UtilDateDeserializer implements JsonDeserializer<java.util.Date> {
@Override
public java.util.Date deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context)
throws JsonParseException {
return new java.util.Date(json.getAsJsonPrimitive().getAsLong());
}
}
Java 代码
1. import java.lang.reflect.Type;
2.
3. import com.google.gson.JsonElement;
4. import com.google.gson.JsonPrimitive;
5. import com.google.gson.JsonSerializationContext;
6. import com.google.gson.JsonSerializer;
7.
8. public class UtilDateSerializer implements JsonSerializer<java.util.Date>
{
9.
10. @Override
11. public JsonElement serialize(java.util.Date src, Type typeOfSrc,
12. JsonSerializationContext context) {
13. return new JsonPrimitive(src.getTime());
14. }
15.
16. }
import java.lang.reflect.Type;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class UtilDateSerializer implements JsonSerializer<java.util.Date> {
@Override
public JsonElement serialize(java.util.Date src, Type typeOfSrc,
JsonSerializationContext context) {
return new JsonPrimitive(src.getTime());
}
}
Java 代码
1. /**
2. * 序列化方法
3. * @param bean
4. * @param type
5. * @return
6. */
7. public static String bean2json(Object bean, Type type) {
8. Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.c
lass, new UtilDateSerializer())
9. .setDateFormat(DateFormat.LONG).create();
10. return gson.toJson(bean);
11. }
12.
13. /**
14. * 反序列化方法
15. * @param json
16. * @param type
17. * @return
18. */
19. public static <T> T json2bean(String json, Type type) {
20. Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.
class, new UtilDateDeserializer())
21. .setDateFormat(DateFormat.LONG).create();
22. return gson.fromJson(json, type);
23. }
/**
* 序列化方法
* @param bean
* @param type
* @return
*/
public static String bean2json(Object bean, Type type) {
Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new
UtilDateSerializer())
.setDateFormat(DateFormat.LONG).create();
return gson.toJson(bean);
}
/**
* 反序列化方法
* @param json
* @param type
* @return
*/
public static <T> T json2bean(String json, Type type) {
Gson gson = new GsonBuilder().registerTypeAdapter(java.util.Date.class, new
UtilDateDeserializer())
.setDateFormat(DateFormat.LONG).create();
return gson.fromJson(json, type);
}
现在开始测试
Java 代码
1. List<TestBean> testBeanList = new ArrayList<TestBean>();
2. TestBean testBean = new TestBean();
3. testBean.setId("id");
4. testBean.setName("name");
5. testBean.setBirthday(new java.util.Date());
6. testBeanList.add(testBean);
7.
8. java.lang.reflect.Type type = new com.google.gson.reflect.TypeToken<List<T
estBean>>() {
9. }.getType();
10. String beanListToJson = bean2json(testBeanList, type);
11. System.out.println("beanListToJson:" + beanListToJson);
12. //prints [{"id":"id","name":"name","birthday":1256531559390}]
13.
14. List<TestBean> testBeanListFromJson = json2bean(beanListToJson, type);
15. System.out.println(testBeanListFromJson);
16. //prints [TestBean@77a7f9[id=id,name=name,birthday=Mon Oct 26 12:39:05 CS
T 2009]]
List<TestBean> testBeanList = new ArrayList<TestBean>();
TestBean testBean = new TestBean();
testBean.setId("id");
testBean.setName("name");
testBean.setBirthday(new java.util.Date());
testBeanList.add(testBean);
java.lang.reflect.Type type = new
com.google.gson.reflect.TypeToken<List<TestBean>>() {
}.getType();
String beanListToJson = bean2json(testBeanList, type);
System.out.println("beanListToJson:" + beanListToJson);
//prints [{"id":"id","name":"name","birthday":1256531559390}]
List<TestBean> testBeanListFromJson = json2bean(beanListToJson, type);
System.out.println(testBeanListFromJson);
//prints [TestBean@77a7f9[id=id,name=name,birthday=Mon Oct 26 12:39:05 CST 2009]]
后记:对于 java.sql.Date 的转化同上类似,写两个类用于其序列化和反序列化即可
SQLDateDeserializer implements JsonDeserializer<java.sql.Date>
SQLDateSerializer implements JsonSerializer<java.sql.Date>
GsonBuilder api :
com.google.gson
Class GsonBuilder
java.lang.Object
com.google.gson.GsonBuilder
public final class GsonBuilderextends Object
Use this builder to construct a Gson instance when you need to set configuration
options other than the default. For Gson with default configuration, it is
simpler to use new Gson(). GsonBuilder is best used by creating it, and then
invoking its various configuration methods, and finally calling create.
The following is an example shows how to use the GsonBuilder to construct a Gson
instance:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Id.class, new IdTypeAdapter())
.serializeNulls()
.setDateFormat(DateFormat.LONG)
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.setVersion(1.0)
.create();
NOTE: the order of invocation of configuration methods does not matter.
Author:
Inderjeet Singh, Joel Leitch
Constructor Summary
GsonBuilder()
Creates a GsonBuilder instance that can be used to build Gson with
various configuration settings.
Method Summary
Gson create()
Creates a Gson instance based on the current
configuration.
GsonBuilder excludeFieldsWithModifiers(int... modifiers)
Configures Gson to excludes all class fields that have
the specified modifiers.
GsonBuilder excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration
for serialization or deserialization that do not have the Expose
annotation.
GsonBuilder registerTypeAdapter(Type type, Object typeAdapter)
Configures Gson for custom serialization or
deserialization.
GsonBuilder serializeNulls()
Configure Gson to serialize null fields.
GsonBuilder setDateFormat(int style)
Configures Gson to to serialize Date objects according
to the style value provided.
GsonBuilder setDateFormat(int dateStyle, int timeStyle)
Configures Gson to to serialize Date objects according
to the style value provided.
GsonBuilder setDateFormat(String pattern)
Configures Gson to serialize Date objects according to
the pattern provided.
GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
Configures Gson to apply a specific naming policy to an
object's field during serialization and deserialization.
GsonBuilder setPrettyPrinting()
Configures Gson to output Json that fits in a page for
批注 [1]: ======== CONSTRUCTOR
SUMMARY ========
批注 [2]:
批注 [3]: ========== METHOD
SUMMARY ===========
批注 [4]:
pretty printing.
GsonBuilder setVersion(double ignoreVersionsAfter)
Configures Gson to enable versioning support.
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
Constructor Detail
GsonBuilder
public GsonBuilder()
Creates a GsonBuilder instance that can be used to build Gson with various
configuration settings. GsonBuilder follows the builder pattern, and it is
typically used by first invoking various configuration methods to set
desired options, and finally calling create().
Method Detail
setVersion
public GsonBuilder setVersion(double ignoreVersionsAfter)
Configures Gson to enable versioning support.
Parameters:
ignoreVersionsAfter - any field or type marked with a version higher
than this value are ignored during serialization or deserialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
excludeFieldsWithModifiers
public GsonBuilder excludeFieldsWithModifiers(int... modifiers)
Configures Gson to excludes all class fields that have the specified
modifiers. By default, Gson will exclude all fields marked transient or
static. This method will override that behavior.
批注 [5]:
批注 [6]: ========= CONSTRUCTOR
DETAIL ========
批注 [7]:
批注 [8]:
批注 [9]: ============ METHOD
DETAIL ==========
批注 [10]:
批注 [11]:
批注 [12]:
Parameters:
modifiers - the field modifiers. You must use the modifiers specified
in the Modifier class. For example, Modifier.TRANSIENT,
Modifier.STATIC.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
excludeFieldsWithoutExposeAnnotation
public GsonBuilder excludeFieldsWithoutExposeAnnotation()
Configures Gson to exclude all fields from consideration for serialization
or deserialization that do not have the Expose annotation.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
serializeNulls
public GsonBuilder serializeNulls()
Configure Gson to serialize null fields. By default, Gson omits all fields
that are null during serialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
setFieldNamingPolicy
public GsonBuilder setFieldNamingPolicy(FieldNamingPolicy namingConvention)
Configures Gson to apply a specific naming policy to an object's field
during serialization and deserialization.
Parameters:
namingConvention - the JSON field naming convention to use for
serialization and deserialization.
批注 [13]:
批注 [14]:
批注 [15]:
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
setPrettyPrinting
public GsonBuilder setPrettyPrinting()
Configures Gson to output Json that fits in a page for pretty printing.
This option only affects Json serialization.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
setDateFormat
public GsonBuilder setDateFormat(String pattern)
Configures Gson to serialize Date objects according to the pattern provided.
You can call this method or setDateFormat(int) multiple times, but only the
last invocation will be used to decide the serialization format.
Note that this pattern must abide by the convention provided by
SimpleDateFormat class. See the documentation in SimpleDateFormat for more
information on valid date and time patterns.
Parameters:
pattern - the pattern that dates will be serialized/deserialized
to/from
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
setDateFormat
public GsonBuilder setDateFormat(int style)
Configures Gson to to serialize Date objects according to the style value
provided. You can call this method or setDateFormat(String) multiple times,
批注 [16]:
批注 [17]:
批注 [18]:
but only the last invocation will be used to decide the serialization
format.
Note that this style value should be one of the predefined constants in the
DateFormat class. See the documentation in DateFormat for more information
on the valid style constants.
Parameters:
style - the predefined date style that date objects will be
serialized/deserialized to/from
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
setDateFormat
public GsonBuilder setDateFormat(int dateStyle,
int timeStyle)
Configures Gson to to serialize Date objects according to the style value
provided. You can call this method or setDateFormat(String) multiple times,
but only the last invocation will be used to decide the serialization
format.
Note that this style value should be one of the predefined constants in the
DateFormat class. See the documentation in DateFormat for more information
on the valid style constants.
Parameters:
dateStyle - the predefined date style that date objects will be
serialized/deserialized to/from
timeStyle - the predefined style for the time portion of the date
objects
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
Since:
1.2
registerTypeAdapter
public GsonBuilder registerTypeAdapter(Type type,
批注 [19]:
批注 [20]:
Object typeAdapter)
Configures Gson for custom serialization or deserialization. This method
combines the registration of an InstanceCreator, JsonSerializer, and a
JsonDeserializer. It is best used when a single object typeAdapter
implements all the required interfaces for custom serialization with Gson.
If an instance creator, serializer or deserializer was previously
registered for the specified type, it is overwritten.
Parameters:
type - the type definition for the type adapter being registered
typeAdapter - This object must implement at least one of the
InstanceCreator, JsonSerializer, and a JsonDeserializer interfaces.
Returns:
a reference to this GsonBuilder object to fulfill the "Builder"
pattern
create
public Gson create()
Creates a Gson instance based on the current configuration. This method is
free of side-effects to this GsonBuilder instance and hence can be called
multiple times.
Returns:
an instance of Gson configured with the options currently set in this
builder
批注 [21]:
发表评论
-
jackJson
2015-05-31 22:19 987在Java平台(StAX, JAXB等)XML处理质量和多 ... -
java网站大全
2015-05-09 23:02 575http://scjp.home.sohu.com/ 模拟试 ... -
my of java网站
2015-05-09 22:48 607MAVEN JAR大全 http://maven.out ... -
jvm性能优化(转载)
2015-04-12 20:05 481JVM内存模型优点 内置基于内存的并发模型: ... -
CGLib动态代理原理及实现
2014-04-02 14:51 511JDK实现动态代理需要实现类通过接口定义业务方法,对于没有接口 ... -
java基础知识总结(一)
2013-04-01 11:30 704一.java基础: 1.java内 ... -
JAVA网络通讯总结一
2013-03-29 17:33 697一.TCP/UDP Sockets 1.TCP需要四个方 ... -
JVM参数调优
2013-03-22 16:54 638JVM参数的含义 实例见实 ... -
list,Object数据转换成json数据
2013-03-18 15:58 852//list转换成json数组 public static ... -
Properties读写文件的操作
2013-03-18 15:01 716Properties读文件 public void readB ... -
获取classpath之外资源路径的方法
2013-02-18 16:19 779// web工程根路径 private static fin ... -
自定义注解
2013-02-18 16:10 404@Retention(RetentionPolicy.RUNT ...
相关推荐
此外,GJSON的序列化和反序列化速度非常快,性能优于许多其他JSON解析库,因此在对性能敏感的应用中,GJSON是一个不错的选择。 总结来说,GJSON是Android开发中处理JSON数据的一个高效工具,它的简洁API使得解析和...
开源项目-tidwall-gjson.zip是一个包含Go语言实现的GJSON库的压缩包。GJSON,全称为"Go JSON",是由tidwall开发的一个高效、轻量级的库,专门用于解析和检索JSON数据。这个库以其快速和简洁的API在Go社区中广受欢迎...
在Golang中,处理JSON数据是一项常见的任务,而`gjson`库提供了一种高效且易用的方式来解析JSON字符串。这个库是由Samuel Stauffer...通过学习和使用`gjson`,你可以更有效地处理JSON数据,提升你的Go应用开发效率。
gjson,全称为GeoJSON,是一种基于JSON的地理空间数据交换格式,广泛用于地理信息系统和Web应用程序中。它能够表示地理空间对象,如点、线、多边形等,并且可以方便地在网络上传输和处理。 描述中提到,这些gjson...
在IT行业中,Go语言(Golang)是一种广泛用于系统编程、网络编程以及微服务开发的高性能编程语言。...无论是用于构建数据库系统,还是在其他需要处理JSON数据的服务或应用中,gjson都能提供高效的解决方案。
在Java世界中,Gson库是Google提供的一款强大的JSON解析工具,它允许我们将Java对象转换为JSON字符串,反之亦然。...无论是开发服务器端应用还是移动应用,熟悉并掌握Gson都能显著提升JSON处理能力。
JSON是互联网上应用最广泛的数据交换格式之一,尤其是在Web服务和前后端交互中。 在Java开发中,处理JSON数据通常需要借助第三方库。标题提到的"网传json格式相关jar包"可能是指某个流行的Java JSON处理库,如...
它使得Java对象可以被转换为JSON格式的字符串,同时也可以将JSON文本解析为等效的Java对象,极大地简化了Java应用程序与JSON之间的交互。在本案例中,我们涉及的是Gson库的版本2.8.5,包含三个jar包,分别是: 1. *...
在Java编程中,枚举类型(Enum)是一种强大的工具,用于定义一组预定义的常量。...通过学习和理解这些示例,你可以更好地理解和应用这种自定义枚举处理策略,使得Gson在处理枚举时更加灵活和适应性强。
标题"Gjosn(围栏列表)"暗示我们正在讨论一个与JSON处理相关的Android应用程序,它特别关注于管理和显示基于地理围栏的数据。这个程序可能用于跟踪、监控或管理地理位置相关的对象或事件,例如安全区域、交通路线或...
压缩包中的"Gjson示例1.txt"、"Gjson示例2.txt"和"Gjson示例3.txt"很可能是包含Gson使用示例的代码文件。这些示例可能涵盖了如何将基本类型、复杂对象、集合、自定义类型转换为JSON,以及如何从JSON数据中解析这些...
它的JSON解析器和序列化器(`glib-2.0`中的`gjson`和`gjson-printer`)提供了高效且易于使用的API来解析JSON文本为数据结构,以及将数据结构转换回JSON字符串。这对于在C语言中处理JSON数据非常有用,而`p6-JSON-...
运行yarn start以在开发模式下启动应用程序。 打开在浏览器中查看它。 如果您进行编辑,则页面将重新加载。 您还将在控制台中看到任何棉绒错误。 您还需要来模拟REST API: sudo npm i json-server -gjson-server ...
利用MFC应用程序、媒体控制接口MIC的基本知识,设计一个MP3播放器。要求能够播放常用Windows音频格式的文件;实现播放控制:播放、暂停、停止等;实现音量控制:静音、声音放大减小;实现播放列表管理:加入文件、...
利用MFC应用程序、媒体控制接口MIC的基本知识,设计一个MP3播放器。要求能够播放常用Windows音频格式的文件;实现播放控制:播放、暂停、停止等;实现音量控制:静音、声音放大减小;实现播放列表管理:加入文件、...
1. **创建**:当用户首次访问应用时。 2. **使用**:在整个会话过程中,可以读取和修改Session中的数据。 3. **销毁**:通常情况下,Session会在一定时间后自动失效,也可以手动销毁。 #### 四、Session的应用场景 ...
在实际应用中,编码和解码JSON数据时,还可能需要考虑空值(empty values)的处理,比如空字符串、零值以及指针类型等,在Go的JSON库中,空值会被编码为JSON的null值。 除了编码和解码,Go语言还提供了其他处理JSON...