开发者

How can I write a multidimensional JSON object in JSP and pass the JSON object back to JavaScript?

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.

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

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);

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

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

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

To Sum up: How can I create a multidimensional objec开发者_如何学Ct 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.


To create a structure like this using Gson:

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

You could do something like this:

<%
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);
%>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜