csdnxpw 2010-12-21
比如一个User对象,我想要一个框架可以直接转换成{id:1001,name='张三'}就目前来看,Google的GSON组件不错,而且支持JDK5的泛型。
地址:http://code.google.com/p/google-gson/
User用户类:
publicclassUser{
@Expose
privateLongid;
@Expose
privateStringname;
publicLonggetId(){
returnid;
}
publicvoidsetId(Longid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
}
//测试JavaBean的转换
publicclassTest{
publicstaticvoidmain(String[]args){
Useruser=newUser();
user.setId(1001L);
user.setName("张三");
GsonBuilderbuilder=newGsonBuilder();
//不转换没有@Expose注解的字段
builder.excludeFieldsWithoutExposeAnnotation();
Gsongson=builder.create();
StringsUser=gson.toJson(user);
System.out.println(sUser);
//{"id":1001,"name":"张三"}
//将JSON字符串转换为JavaBean
Useruser2=gson.fromJson(sUser,User.class);
System.out.println(user2.getId()+","+user2.getName());
//1001,张三
}
}
//测试HashMap的转换
publicclassMapTest{
publicstaticvoidmain(String[]args){
Useruser1=newUser();
user1.setId(1001L);
user1.setName("张三");
Useruser2=newUser();
user2.setId(1002L);
user2.setName("李四");
MapuserMap=newHashMap();
userMap.put("user1",user1);
userMap.put("user2",user2);
GsonBuilderbuilder=newGsonBuilder();
//不转换没有@Expose注解的字段
builder.excludeFieldsWithoutExposeAnnotation();
Gsongson=builder.create();
StringsUserMap=gson.toJson(user,newTypeToken>(){}.getType());
System.out.println(sUserMap);
//{"user1":{"id":1001,"name":"张三"},"user2":{"id":1002,"name":"李四"}}
//将JSON字符串转换为HashMap
MapuserMap2=(Map)gson.fromJson(sUser,newTypeToken>(){}.getType());
System.out.println(userMap2.get("user1").getName());
//张三
}
}
当然GSON的JSON解析设置还不止这些,还有版本的注解、更改字段名称的注解等等。
上面给的网址上有具体的开发文档,和详细的例子。
如今GSON已被很多公司所采用,方便快捷。Google就是比较强大。</STRING,></STRING,></STRING,></STRING,></STRING,></STRING,>
.create();String param = "xxxxxxx";Map<String, Map<String, List<MpAppInfo>>> inParams = gson.fromJso