Cómo devuelve un objeto JSON desde un Servlet Java


Cómo se devuelve un objeto JSON de un servlet Java.

Anteriormente, al hacer AJAX con un servlet, he devuelto una cadena. ¿Hay un tipo de objeto JSON que necesita ser utilizado, o simplemente devuelve una cadena que se parece a un objeto JSON, por ejemplo,

String objectToReturn = "{ key1: 'value1', key2: 'value2' }";
Author: rodrigo-silveira, 2010-01-06

10 answers

Hago exactamente lo que me sugieres (devuelve un String).

Podría considerar establecer el tipo MIME para indicar que está devolviendo JSON, aunque (de acuerdo con este otro post de stackoverflow es "application/json").

 48
Author: Mark Elliot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:03:07

Escriba el objeto JSON en el flujo de salida del objeto response.

También debe establecer el tipo de contenido de la siguiente manera, que especificará lo que está devolviendo:

response.setContentType("application/json");
// Get the printwriter object from response to write the required json object to the output stream      
PrintWriter out = response.getWriter();
// Assuming your json object is **jsonObject**, perform the following, it will return your json object  
out.print(jsonObject);
out.flush();
 162
Author: user241924,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-06 22:02:40

Primero convierta el objeto JSON a String. Luego simplemente escríbalo al escritor de respuestas junto con el tipo de contenido de application/json y la codificación de caracteres de UTF-8.

Aquí hay un ejemplo asumiendo que estás usando Google Gson para convertir un objeto Java en una cadena JSON:

protected void doXxx(HttpServletRequest request, HttpServletResponse response) {
    // ...

    String json = new Gson().toJson(someObject);
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    response.getWriter().write(json);
}

Eso es todo.

Véase también:

 76
Author: BalusC,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:24

Cómo se devuelve un objeto JSON desde un Servlet Java

response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();

  //create Json Object
  JsonObject json = new JsonObject();

    // put some value pairs into the JSON object .
    json.put("Mobile", 9999988888);
    json.put("Name", "ManojSarnaik");

    // finally output the json string       
    out.print(json.toString());
 25
Author: MAnoj Sarnaik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-06 06:16:36

Simplemente escriba una cadena en el flujo de salida. Puede establecer el tipo MIME en text/javascript (editar: application/json es aparentemente oficialista) si te sientes útil. (Hay una pequeña pero distinta de cero posibilidad de que evitará que algo lo arruine algún día, y es una buena práctica.)

 8
Author: fennec,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-01-06 04:43:55

Gson es muy útil para esto. incluso más fácil. este es mi ejemplo:

public class Bean {
private String nombre="juan";
private String apellido="machado";
private List<InnerBean> datosCriticos;

class InnerBean
{
    private int edad=12;

}
public Bean() {
    datosCriticos = new ArrayList<>();
    datosCriticos.add(new InnerBean());
}

}

    Bean bean = new Bean();
    Gson gson = new Gson();
    String json =gson.toJson(bean);

Fuera.print(json);

{"nombre":"juan","apellido":"machado","datosCriticos":[{"edad":12}]}

Tiene que decir gente si sus vars están vacíos cuando usa gson, no construirá el json para usted.Solo el

{}

 8
Author: superUser,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-24 03:02:20

Puede haber un objeto JSON para la conveniencia de codificación Java. Pero por fin la estructura de datos será serializada en cadena. Establecer un tipo MIME adecuado sería bueno.

Yo sugeriría JSON Java desde json.org .

 6
Author: nil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-23 13:36:22

Usé Jackson para convertir un objeto Java a una cadena JSON y enviarlo de la siguiente manera.

PrintWriter out = response.getWriter();
ObjectMapper objectMapper= new ObjectMapper();
String jsonString = objectMapper.writeValueAsString(MyObject);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
out.print(jsonString);
out.flush();
 5
Author: ravthiru,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-16 06:46:39

Respuesta.setContentType ("text/json");

//cree la cadena JSON, sugiero usar algún framework.

String your_string;

Fuera.write (your_string.getBytes("UTF-8"));

 3
Author: RHT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-03 13:28:05

Cerca de BalusC responder en 4 líneas simples usando Google Gson lib. Agregue estas líneas al método servlet:

User objToSerialize = new User("Bill", "Gates");    
ServletOutputStream outputStream = response.getOutputStream();

response.setContentType("application/json;charset=UTF-8");
outputStream.print(new Gson().toJson(objToSerialize));

¡Buena suerte!

 0
Author: Panayot Kulchev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-23 06:08:09