环境说明:
JDK 1.5以上,GSon 2.2.2。
阅读对象:
假设读者已经了解Java注解的使用以及如何创建一个指定注解类型,读者对JSON、GSON有基本了解,对Java反射机制有所了解。
需求概述:开发一个日志记录、显示功能,要求当对指定的实体类进行新增、删除、修改操作时,将变化的内容记录到日志表中。
格式要求:
字段中文名:字段值,比如:用户名:张三。
首先新建两个实体类:
package com.gson.tutorial;
import java.util.Date;
public class MySuperEntity {
private long id;
private String name;
private Date date;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
package com.gson.tutorial;
import java.util.Date;
import com.google.gson.annotations.Expose;
import com.gson.tutorial.annotation.FieldComment;
public class MyEntity {
@Expose
@FieldComment("用户ID")
private long id;
@Expose
@FieldComment("用户名")
private String userName;
private String address;
private Date date;
private MySuperEntity entity;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public MySuperEntity getEntity() {
return entity;
}
public void setEntity(MySuperEntity entity) {
this.entity = entity;
}
}
上面的类中,字段上的@Expose是GSON的注解,表示该字段在进行JSON转换时保留,也就是没有该注解的字段将在进行JSON转换时被忽略。
@FieldComment注解是一个自定义的注解类型,用于填写字段的中文说明,该自定义注解的源码为:
package com.gson.tutorial.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface FieldComment {
String value();
}
下面写一个测试用例:
package com.gson.tutorial;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
MyEntity entity = new MyEntity();
entity.setId(123456L);
entity.setUserName("Test User");
entity.setAddress("金茂中路");
entity.setDate(new Date());
String json = gson.toJson(entity);
System.out.println("Using Expose:" + json);
gson = new Gson();
json = gson.toJson(entity);
System.out.println("Unusing Expose:" + json);
}
}
输出结果为:
Using Expose:{"id":123456,"userName":"Test User"}
Unusing Expose:{"id":123456,"userName":"Test User","address":"金茂中路","date":"Sep 23, 2012 11:33:42 PM"}
可以看到,如果使用:
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
方式进行JSON转换,那么被@Expose注解的字段将被转成JSON,其他字段将被忽略。而传统的GSON转换方式则不会理会@Expose注解。
接着进行格式转换输出:
package com.gson.tutorial.annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.gson.tutorial.MyEntity;
public class Main {
/**
* @param args
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalAccessException
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void main(String[] args) throws ClassNotFoundException,
IllegalAccessException, InvocationTargetException {
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
.create();
MyEntity entity = new MyEntity();
entity.setId(123456L);
entity.setUserName("Test User");
entity.setAddress("金茂中路");
entity.setDate(new Date());
String json = gson.toJson(entity);
System.out.println("Using Expose:" + json);
// -------------------------------------
String className = "com.gson.tutorial.MyEntity";
Class classDef = Class.forName(className);
Object logObj = gson.fromJson(json, classDef);
Field[] fields = classDef.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
boolean isPresent = fields[i]
.isAnnotationPresent(FieldComment.class);
if (isPresent) {
// 取注解中的文字说明
FieldComment comment = fields[i]
.getAnnotation(FieldComment.class);
String fieldComment = comment.value();
// 取对象中字段的值
fields[i].setAccessible(true); // 设置为可访问private字段
Object fieldValue = fields[i].get(logObj);
String content = String.format("%s:%s", fieldComment,
fieldValue);
System.out.println(content);
}
}
}
}
输出结果:
Using Expose:{"id":123456,"userName":"Test User"}
用户ID:123456
用户名:Test User
分享到:
相关推荐
Gson解析之自定义序列化和反序列化的代码例子,但后端对同一个字段给的数据类型与文档不一致时的处理
赠送jar包:gson-2.8.0.jar; 赠送原API文档:gson-2.8.0-javadoc.jar; 赠送源代码:gson-2.8.0-sources.jar; 赠送Maven依赖信息文件:gson-2.8.0.pom; 包含翻译后的API文档:gson-2.8.0-javadoc-API文档-中文...
利用Gson.jar 实现快速将对象类型转换为json
Volley访问网络,Gson解析,自定义Adapter显示网络图片和文字
om.google.code.gson/gson/2.6.2 Gson maven依赖 java 开发包
自定义 android volley Gson 解析方式
android程序利用gson和async的网络请求完整代码!
介绍:Gson 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. 压缩包里有以下文件: ...
GitHub上的开源项目。GSON是Google开发的Java API,用于转换Java对象和Json对象。
Android Studio下使用Google Gson解析Json数据示例
实际下载地址在:http://repo1.maven.org/maven2/com/google/code/gson/gson/ 感谢 Milan__Kundera 提供
利用Google Gson实现JSON字符串和对象之间相互转换,内含源码和jar包
文件包括(1.GSON的jar包。2.GSON的源码。3.Gson的HTML和CHM的API文档)。统一版本号2.2.4。 JavaScript在编程语言中一直很热门.JSON...GSON在以Java开发的C/S(包括B/S)中有很好的发挥,GSON是Google开发的。
1、生成Json数据 2、使用Gson解析Json数据(单个json对象、json数组和json对象内嵌json数组) // 这里有两篇好心人的博文,有详细的讲解 http://www.jb51.net/article/32547.htm ...
JsonAnnotation利用注解自动生成Gson‘s Model的库.rar,太多无法一一验证是否可用,程序如果跑不起来需要自调,部分代码功能进行参考学习。
包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class ...
json我们在网络请求中经常用到,最近最火的微信小程序开发中更是必不可少。平常我们都是用net.sf.json.JSONObject来把对象转为json,但是当对象是一个对象列表如:List<Users> list =new ArrayList(); 用户列表对象...
Google发布的gson 2.1版本,专用于json格式的数据与java对象的互相转化,功能十分强大
gson jar包 gson jar包下载 gson jar包下载 gson jar包下载
非常详细的json使用方法。包括对象和json之间的相互转换,集合和json之间的相互转换,自己按照节点解析。gson功能真的很强大。