Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the JSP equivalent to json_encode ( in PHP )?

I am trying to encode a JSP servlet into JSON. What's the equivalent in JSP to json_encode() in PHP ?

like image 385
jeph perro Avatar asked Jul 08 '10 19:07

jeph perro


People also ask

What is json_encode function 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.

What is json_encode in JavaScript?

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.

How do you JSON encode HTML in PHP?

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.

How can access JSON encode data in PHP?

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.


1 Answers

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.

like image 59
BalusC Avatar answered Oct 19 '22 08:10

BalusC