I am trying to encode a JSP servlet into JSON. What's the equivalent in JSP to json_encode() in PHP ?
The json_encode() function is an inbuilt function in PHP which is used to convert PHP array or object into JSON representation. Syntax : string json_encode( $value, $option, $depth ) Parameters: $value: It is a mandatory parameter which defines the value to be encoded.
The PHP json_encode function translates the data passed to it to a JSON string which can then be output to a JavaScript variable. We demonstrate on this page with single level arrays. Other pages demonstrate using json_encode with multi-dimensional arrays and scalar values.
php $data = '{ "name": "John Doe", "occupation": "gardener" }'; $a = json_decode($data, true); header('Content-type:text/html;charset=utf-8'); echo "{$a["name"]} is a {$a["occupation"]}"; The example transforms a JSON string into a PHP variable.
To receive JSON string we can use the “php://input” along with the function file_get_contents() which helps us receive JSON data as a file and read it into a string. Later, we can use the json_decode() function to decode the JSON string.
JSP/Servlet isn't that high-level as PHP which has practically "anything built-in". In Java you've more freedom to choose from libraries. There are several JSON libraries in Java available which you can implement in your webapp, the popular ones being under each JSON.org, Jackson and Google Gson.
We use here Gson to our satisfaction. It has excellent support for parameterized collections and (nested) Javabeans. It's basically as simple as follows:
String json = new Gson().toJson(anyObject); // anyObject = List<Bean>, Map<K, Bean>, Bean, String, etc..
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Converting JSON to a fullworthy Javabean is also simple with Gson, see this example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With