Java对象与JSON字符串互转
包下载 地址 : http://download.youkuaiyun.com/detail/chenyi0834/4499629
废话不多说,直接上代码。
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));
}
}
}