我目前正在尝试用JSP语言编写一个多维对象或数组,然后将其传递回来自JavaScript的AJAX调用。现在,使用AJAX解码一个JSON对象(jQuery JSON)。所以,我在这方面做得很好。
但是我在JSP中创建多维JSON对象或数组时迷失了方向。
我一直在研究JSON plugin for JSP (http://code.google.com/p/json-simple/)的json-simple。不仅仅是这个插件,我在JSP中也找不到任何多维JSON对象或数组示例。
例如,我得到了这个例子,但它是一维的:
//import org.json.simple.JSONObject;
JSONObject obj=new JSONObject();
obj.put("name","foo");
obj.put("num",new Integer(100));
obj.put("balance",new Double(1000.21));
obj.put("is_vip",new Boolean(true));
obj.put("nickname",null);
System.out.print(obj);
我希望JSON对象的结果如下:
{
"results": [ {
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": [ "street_number" ]
} ],
} ]
}
然后,我会将其传递回JavaScript并进行解码。
总结:如何在JSP中创建多维对象或数组?JSON插件无关紧要;无论如何工作,我都会非常高兴。
如果有任何帮助,我将不胜感激。提前谢谢你。
发布于 2011-05-12 03:05:20
要使用Gson创建这样的结构
{
"results": [ {
"address_components": [ {
"long_name": "1600",
"short_name": "1600",
"types": [ "street_number" ]
} ],
} ]
}
你可以这样做:
<%
String[] types = {"street_number"};
Hashtable address_components = new Hashtable();
address_components.put("long_name", 1600);
address_components.put("short_name", 1600);
address_components.put("types", types);
Hashtable results = new Hashtable();
results.put("address_components", address_components);
// Make sure you have the Gson JAR in your classpath
// (place it in the tomcat/classes directory)
com.google.gson.Gson gson = new com.google.gson.Gson();
String json = gson.toJson(obj);
out.print(json);
%>
https://stackoverflow.com/questions/5969164
复制相似问题