标签云

微信群

扫码加入我们

WeChat QR Code

How do you return a JSON object form a Java servlet.

Previously when doing AJAX with a servlet I have returned a string. Is there a JSON object type that needs to be used, or do you just return a String that looks like a JSON object e.g.

String objectToReturn = "{ key1: 'value1', key2: 'value2' }";


Nitpick; shouldn't you want more like { key1: value1, key2: value2 }?

2018年09月24日39分21秒

Nitpick: what he really wants is { "key1": "value1", "key2": "value2" }... :-)

2018年09月24日39分21秒

Ankur checkout the link if you decided to use Spring 3.2.0.

2018年09月25日39分21秒

Nitpick: we shouldn't assume the values are Strings, so what he really wants is { "key1": value1, "key2": value2 }

2018年09月24日39分21秒

This helped me. As mentioned in Mark Elliot answer, jsonObject could be just a string formatted as a json. Remember to use double quotes, as single quotes won't give you a valid json. Ex.: String jsonStr = "{\"my_key\": \"my_value\"}";

2018年09月25日39分21秒

It will be good to use response.setCharacterEncoding("utf-8"); too

2018年09月25日39分21秒

I'm doing this to send response to javascript and displaying the response in alert. why is it displaying the html code inside the alert..why am i getting the html code as response. i did the exact same thing like you said.

1970年01月01日00分03秒

I have the same issue as iLive

2018年09月24日39分21秒

Incorrect. There is usually no reason to add overhead of constructing a String -- output should go straight to OutputStream. Or, if intermediate form is needed for some reason, can use byte[]. Most Java JSON libraries can write directly to OutputStream.

2018年09月24日39分21秒

do I need to use getBytes("UTF-8")) or can I just return the String variable?

2018年09月24日39分21秒

It's a safe programming practice to use UTF-8 for encoding the response of a web application.

2018年09月24日39分21秒