最近在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("[email protected]"); 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("[email protected]"); Account account2 = new Account(); account2.setId(2); account2.setUsername("bowen"); account2.setPassword("123"); account2.setEmail("[email protected]"); 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":"[email protected]"} Convert Json String to Bean... Account:[email protected] Convert Bean list to Json String... [{"id":0,"username":"bowen","password":"123","email":"[email protected]"},{"id":1,"username":"bowen","password":"123","email":"[email protected]"},{"id":2,"username":"bowen","password":"123","email":"[email protected]"}] Convert Json String to Bean list... [email protected] [email protected] [email protected]
个人比较懒,对于实现同一个功能,还是越简单越好啦~
时间: 2024-11-08 09:00:13