最近在Web开发中,用到Json和Ajax传数据,需要实现对象和Json字符串的转换,尝试了多种方法和类库,发现还是Gson比较好用。
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,反之亦可。
jar包下载地址:http://code.google.com/p/google-gson/downloads/list;
不过Goole有时访问不了,可以用这个地址:http://mvnrepository.com/search?q=gson;
更详细的内容可以参考这个博客:http://blog.csdn.net/lk_blog/article/details/7685169。
下面动手实现一个简单的Gson测试Demo:
package com.demo.util;
import java.util.ArrayList;
import java.util.List;
import com.demo.domain.Account;
import com.google.gson.*;
import com.google.gson.reflect.TypeToken;
public class GsonTest {
public static void main(String[] args){
Gson gson =new Gson();
Account account = new Account();
account.setId(0);
account.setUsername("bowen");
account.setPassword("123");
account.setEmail("123@qq.com");
System.out.println("Convert Bean to Json String...");
String strJson1 = gson.toJson(account);
System.out.println(strJson1);
System.out.println("Convert Json String to Bean...");
Account account0 = gson.fromJson(strJson1, Account.class);
System.out.println("Account:"+account0);
Account account1 = new Account();
account1.setId(1);
account1.setUsername("bowen");
account1.setPassword("123");
account1.setEmail("123@qq.com");
Account account2 = new Account();
account2.setId(2);
account2.setUsername("bowen");
account2.setPassword("123");
account2.setEmail("123@qq.com");
List<Account> list = new ArrayList<Account>();
list.add(account0);
list.add(account1);
list.add(account2);
System.out.println("Convert Bean list to Json String...");
String strJson2 = gson.toJson(list);
System.out.println(strJson2);
System.out.println("Convert Json String to Bean list...");
List<Account> accountList = gson.fromJson(strJson2,
new TypeToken<List<Account>>(){}.getType());
for(Account a: accountList){
System.out.println(a);
}
}
}
运行结果:
Convert Bean to Json String...
{"id":0,"username":"bowen","password":"123","email":"123@qq.com"}
Convert Json String to Bean...
Account:com.demo.domain.Account@44bd928a
Convert Bean list to Json String...
[{"id":0,"username":"bowen","password":"123","email":"123@qq.com"},{"id":1,"username":"bowen","password":"123","email":"123@qq.com"},{"id":2,"username":"bowen","password":"123","email":"123@qq.com"}]
Convert Json String to Bean list...
com.demo.domain.Account@1bc74f37
com.demo.domain.Account@3a21b220
com.demo.domain.Account@7a3570b0个人比较懒,对于实现同一个功能,还是越简单越好啦~
原文地址:http://blog.csdn.net/dutsoft/article/details/41675887