日期:2014-05-16  浏览次数:20417 次

JAVA使用JSON之Google Gson

? <pre>比如一个User对象,我想要一个框架可以直接转换成{id:1001,name='张三'} </pre>

<pre>就目前来看,Google的GSON组件不错,而且支持 JDK5 的泛型。
地址:<a href="http://code.google.com/p/google-gson/">http://code.google.com/p/google-gson/</a>

User 用户类:
public class User {
@Expose
private Long id;
@Expose
private String name;

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;
}
}

// 测试 JavaBean 的转换
public class Test {
??? public static void main(String[] args) {
??????? User user = new User();
??????? user.setId(1001L);
??????? user.setName("张三");
??????? GsonBuilder builder = new GsonBuilder();
??????? // 不转换没有 @Expose 注解的字段
??????? builder.excludeFieldsWithoutExposeAnnotation();
??????? Gson gson = builder.create();
?????? ?
??????? String sUser = gson.toJson(user);
??????? System.out.println(sUser);
??????? // {"id":1001,"name":"张三"}
?????? ?
??????? // 将JSON字符串转换为 JavaBean
??????? User user2 = gson.fromJson(sUser, User.class);
??????? System.out.println(user2.getId() + ", " + user2.getName());
??????? // 1001, 张三
??? }
}

// 测试 HashMap 的转换
public class MapTest {
??? public static void main(String[] args) {
??????? User user1 = new User();
??????? user1.setId(1001L);
??????? user1.setName("张三");
??????? User user2 = new User();
??????? user2.setId(1002L);
??????? user2.setName("李四");
??????? Map userMap = new HashMap();
??????? userMap.put("user1", user1);
??????? userMap.put("user2", user2);
??????? GsonBuilder builder = new GsonBuilder();
??????? // 不转换没有 @Expose 注解的字段
??????? builder.excludeFieldsWithoutExposeAnnotation();
??????? Gson gson = builder.create();
?????? ?
??????? String sUserMap = gson.toJson(user, new TypeToken&gt;(){}.getType());
??????? System.out.println(sUserMap);
??????? // {"user1":{"id":1001,"name":"张三"},"user2":{"id":1002,"name":"李四"}}
?????? ?
??????? // 将JSON字符串转换为 HashMap
??????? Map userMap2 = (Map)gson.fromJson(sUser, new TypeToken&gt;(){}.getType());
??????? System.out.println(userMap2.get("user1").getName());
??????? // 张三
??? }
}

当然 GSON的JSON解析设置还不止这些,还有版本的注解、更改字段名称的注解等等。
上面给的网址上有具体的开发文档,和详细的例子。
如今 GSON 已被很多公司所采用,方便快捷。Google就是比较强大。&