我認爲(其實我知道!)我在這裏做錯了一些錯誤,我試圖將一些值填充到HashMap中,並將每個hasmap添加到將被添加到JSON對象:從Servlet返回到Javascript/JSP頁面的JSON響應
JSONObject json = new JSONObject();
try
{
Map address;
List addresses = new ArrayList();
int count = 15;
for (int i=0 ; i<count ; i++)
{
address = new HashMap();
address.put("CustomerName" , "Decepticons" + i);
address.put("AccountId" , "1999" + i);
address.put("SiteId" , "1888" + i);
address.put("Number" , "7" + i);
address.put("Building" , "StarScream Skyscraper" + i);
address.put("Street" , "Devestator Avenue" + i);
address.put("City" , "Megatron City" + i);
address.put("ZipCode" , "ZZ00 XX1" + i);
address.put("Country" , "CyberTron" + i);
addresses.add(address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.setContentType("application/json");
response.getWriter().write(json.toString());
我的問題是我知道這是返回一個字符串,我似乎無法解析(這是問題)。我的問題是,如何返回實際的JSON編碼的字符串(或者甚至應該這樣做?)或針對此類問題的最佳攻擊方法是什麼。我爲此使用的JavaScript如下所示:
function getReadyStateHandler(req)
{
// Return an anonymous function that listens to the
// XMLHttpRequest instance
return function()
{
// If the request's status is "complete"
if (req.readyState == 4)
{
// Check that a successful server response was received
if (req.status == 200)
{
msgBox("JSON Response recieved...");
populateDatagrid(req.responseText.toJSON());
}
else
{
// An HTTP problem has occurred
alert("HTTP error: " + req.status);
}
}
}
}
請注意,JSON響應返回正常,但它是一個字符串。任何意見是極大的讚賞。我也開始使用谷歌Gson,但沒有太多的知識。
你不應該試圖創建一個JSON編碼的字符串;如果您的服務器端代碼沒有提供庫函數來正確地將對象編碼爲JSON編碼的字符串,我會感到非常驚訝。 – 2011-05-28 08:54:27
[Create JSON obect並將其轉換爲Java中的字符串]的可能重複(http://stackoverflow.com/questions/5685613/create-json-obect-and-convert-it-to-string-in-java) – 2011-05-28 08:58:09