如何在JSP中编写多维JSON对象并将JSON对象传递回JavaScript? [英] How can I write a multidimensional JSON object in JSP and pass the JSON object back to JavaScript?

查看:109
本文介绍了如何在JSP中编写多维JSON对象并将JSON对象传递回JavaScript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试在JSP中编写多维对象或数组,然后将其传递回JavaScript中的AJAX调用.现在,使用我已经知道的AJAX(jQuery JSON)解码JSON对象.所以,我在这方面表现很好.

I am currently trying to write a multidimensional object or array in JSP and then pass it back to an AJAX call from JavaScript. Now, decoding a JSON object using AJAX I have figured out (jQuery JSON). So, I'm good on that front.

但是我迷失了在JSP中创建多维JSON对象或数组的方法.

But I am lost on creating a multidimensional JSON object or array in JSP.

我一直在寻找JSP的JSON插件的json-simple(http://code.google.com/p/json-simple/).而且不仅是这个插件,而且我无法在JSP中找到多维JSON对象的任何示例或数组示例.

I have been looking at json-simple for the JSON plugin for JSP (http://code.google.com/p/json-simple/). And it's not just this plugin, but I have been unable to find any examples of multidimensional JSON objects or array examples in JSP.

就像,我得到了这个例子,但是它是一维的:

Like, I get this example but it's one-dimensional:

//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对象具有这样的结果:

I would like the JSON object to have a result like this:

{
  "results": [ {
    "address_components": [ {
      "long_name": "1600",
      "short_name": "1600",
      "types": [ "street_number" ]
    } ],
  } ]
}

然后,我将其传递回JavaScript并对其进行解码.

Then, I'd pass it back to JavaScript and decode it.

总结:如何在JSP中创建多维对象或数组? JSON插件无关紧要;不管做什么,我都会很高兴.

To Sum up: How can I create a multidimensional object or array in JSP? The JSON plugin is inconsequential; whatever works, I'll be more than happy.

我将不胜感激.预先谢谢你.

I would appreciate any help. Thank you in advance.

推荐答案

要使用 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);
%>

这篇关于如何在JSP中编写多维JSON对象并将JSON对象传递回JavaScript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆