如何在jsp中读取json响应

时间:2013-05-10 11:33:36

标签: java javascript json jsp

我的客户端程序是这样的:

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse res = httpClient.execute(req); 

服务器端,我已经编写了一个JSON响应。

JSONObject JObject = new JSONObject();
JObject.put("ResponseCode", "100");
JObject.put("Status", "Success");
response.setContentType("application/json");    
PrintWriter out = response.getWriter();
out.print(JObject);
out.flush();

我如何阅读客户端的ResponseCodeStatus

3 个答案:

答案 0 :(得分:0)

您必须将JSOn字符串转换为对象。如果您使用Javascript,则可以使用JSON.parse(json_str)$.parseJSON(如果您使用jQuery)。完成后,您可以照常访问这些条目:

var obj = JSON.parse(json_str);
var code = obj["ResponseCode"];

修改

使用Java:

JSONObject obj = new JSONObject(json_string);
String code = obj.getString("ResponseCode");

答案 1 :(得分:0)

HttpResponse res = client.execute(req);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

String line = "";
line = rd.readLine();  /// Json Data

答案 2 :(得分:0)

这样的事情:

StatusLine statusLine = res.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) // or whatever 
                {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content, "utf-8"));
String line;
while ((line = reader.readLine()) != null) 
{
    builder.append(line);
}

sRet = builder.toString();

...

tknr = new JSONTokener(sRet);