Java对象与JSON字符串互转
Uncategorized, by admin.
现在产品中有个功能就是要和前台jsp页面进行比较大的数据交换,故考虑用JSON进行数据交换。原来用的这个JSON lib,说实话真的很不好用,看文档貌似还只是到JDK 1.5。在这个阴暗的周末,莫名地感冒了,就给自己找个借口一直赖在床上。写完前面设计模式的博客之后,有了找个好用的JSON库的想法。
在JSON的官网上看到gson的链接,这是Google实现的一个JSON的库。点进去之后,看目标里面第一条就深深地吸引了我,这真是给我这种懒人准备的。
Provide simple
toJson()
andfromJson()
methods to convert Java
立马下载,写了个简单的demo,非常满足我的需求,人生又美好了一点点。
下面是的示例代码,更多的例子,请参考官方的教程,总之使用非常方便。
废话不多说,直接上代码。
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
/**
* Gson的一个简单示例
*
* @author Gythialy
*/
public class TestHashMap {
public static void main(String[] args) {
// 组织示例数据
HashMap<String, List<String>> exportInfo = new HashMap<String, List<String>>();
for (int i = 0; i < 10; i++) {
String className = "classname" + i;
List<String> properties = new ArrayList<String>();
for (int j = 0; j < 5; j++) {
properties.add(className + "-property" + j);
}
exportInfo.put(className, properties);
}
// 转换成JSON字符串
Gson gson = new Gson();
String json = gson.toJson(exportInfo);
System.out.println(json);
// 把JSON字符串转换成原来的Java对象
Type type = new TypeToken<HashMap<String, List<String>>>() {
}.getType();
HashMap<String, List<String>> fromJson = gson.fromJson(json, type);
for (String key : fromJson.keySet()) {
List<String> list = fromJson.get(key);
list.toString();
System.out.println(String.format("%s:%s", key, list));
}
}
}