gson是google解析json的一个开源框架,同类的框架fastJson,JackJson等。
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>();
map.put("s", "\u003chtml\u003e");
Gson gson = new GsonBuilder().disableHtmlEscaping().create(); //disableHtmlEscaping
String json = gson.toJson(map);
System.out.println(json);
}
//运行结果:
{"s":"<html>"}
//[注] 如果在创建gson时不使用disableHtmlEscaping,则运行结果将会是:
{"s":"\u003chtml\u003e"}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
示例结果:
import java.lang.reflect.Type;
import com.google.gson.reflect.TypeToken;
public class Test {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Type type = new TypeToken<HashSet<String>>(){}.getType();
Set<String> set = new HashSet<String>();
set.add("张三");
set.add("李四");
set.add("小娟");
String json = gson.toJson(set);
System.out.println(json);
Set<String> fromJson = gson.fromJson(json, type);
System.out.println(fromJson);
}
}