【问题标题】:How can I write a multidimensional JSON object in JSP and pass the JSON object back to JavaScript?如何在 JSP 中编写多维 JSON 对象并将 JSON 对象传回 JavaScript?
【发布时间】:2011-08-23 13:45:44
【问题描述】:

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

但我在 JSP 中创建多维 JSON 对象或数组时迷失了方向。

我一直在寻找用于 JSP 的 JSON 插件的 json-simple (http://code.google.com/p/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 插件无关紧要;不管怎样,我会很高兴的。

如果有任何帮助,我将不胜感激。提前谢谢你。

【问题讨论】:

    标签: arrays json jsp object multidimensional-array


    【解决方案1】:

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

    【讨论】:

    • 哇。谢谢你。这看起来真的很好。但是,我复制了他的行“JSONObject obj = new JSONObject();” (不带引号)进入 JSP 页面,它会产生 HTTP 500 错误,这意味着存在错误。如何导入以及必须导入什么库才能支持 JSP 页面中的 JSONObject?再次感谢。
    • 您需要一个 JSON 库(通常是一个 JAR 文件)并使用它。我已经使用 Gson 更新了代码。
    • 实际上,我确实还有一个与此讨论相关的问题:如果您查看我上面用来提出问题的示例,您将看到哈希表“address_components”。我怎样才能拥有多个 address_components?我将数据从 SQL 传递到最终的 JSON 对象,但它只是获取循环中的最后一组数据,这有意义吗?我希望 address_components 哈希表像一个数组一样工作。因此,在另一种语言中,我可以访问这样的值:results->address_components[2]->long_name。我希望这是有道理的。谢谢。
    • 将结果更改为数组而不是哈希表,您应该一切顺利。
    猜你喜欢
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    • 2013-07-03
    • 2023-03-27
    • 2012-06-10
    • 2020-02-23
    • 2011-08-24
    • 1970-01-01
    相关资源
    最近更新 更多