'how to read json response in jsp
My client side program is like this:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse res = httpClient.execute(req);
Server side, I have composed a JSON response.
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();
How can i read this ResponseCode
and Status
in Client side back.
Solution 1:[1]
HttpResponse res = client.execute(req);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
line = rd.readLine(); /// Json Data
Solution 2:[2]
Something like this:
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);
Solution 3:[3]
You will have to convert the JSOn string to an object. If using Javascript you can use JSON.parse(json_str)
or $.parseJSON
if you use jQuery. After you have done it you can access those entries as usual:
var obj = JSON.parse(json_str);
var code = obj["ResponseCode"];
Edit
Using Java:
JSONObject obj = new JSONObject(json_string);
String code = obj.getString("ResponseCode");
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Suhas Gaikwad |
Solution 2 | Manuel del Castillo |
Solution 3 |