将map转化为json:
//后台Map map = new HashMap();
map.put("aaa","bbb");
map.put("ccc","ddd");
/*
* json有两种格式 一种是{}对象格式 一种是[{},{}]数组格式
*/
JsonObject json = JsObject.fromObject(map);// 对象格式
// JsonArray json = JSONArray.fromObject(map);//数组格式
System.out.println(json);
HttpServletResponse response = ServletActionCotext.getResponse();
response.setContentType("application/json,charset=utf-8");
out.print(json.toString());
out.flush();
out.close();
前台:
$.getJSON("TestServlet",
"type=list",
function(data){
for(var i in data){
alert (data[i]);
}
}
)
将json转化为map
ObjectMapper mapper = new ObjectMapper();
String s = "{\"name\":\"萧远山\",\"sex\":\"男\",\"age\":23}";
try {
Map<?,?> map = mapper.readValue(s.getClass());
Iterator<?> iterator = map.keySet().iterator();
while(iterator.hasNext()){
Object key = iterator.next();
System.out.print(key+":");
System.out.println(map.get(key).toString());
}
} catch (Exception e) {
e.printStackTrace();
}
将任一对象转化为json对象
JSONMapper.toJSON(random object).render(true);
将一个json对象转化为其他类型对象
JSONValue jsonvalue = new JSONParser(new StringReader{a json object}).nextValue();
JSONMapper.toJava(value,other class);
将json对象输出
Map map = new HashMap();
map.put("aaa","bbb");
map.put("ccc","ddd");
/*
* json有两种格式
* 一种是{}对象格式
* 一种是[{},{}]数组格式
* */
JsonObject json = JsObject.fromObject(map);//对象格式
//JsonArray json = JSONArray.fromObject(map);//数组格式
System.out.println(json);
HttpServletResponse response = ServletActionCotext.getResponse();
response.setContentType("application/json,charset=utf-8");
out.print(json.toString());
out.flush();
out.close();