servicio web jersey codificación json utf-8


Hice un pequeño Rest webservice usando Jersey 1.11. Cuando llamo a la url que devuelve Json, hay problemas con la codificación de caracteres para caracteres no ingleses. La url correspondiente para Xml ("test.xml " lo convierte en utf-8 en la etiqueta xml de inicio.

¿Cómo puedo hacer la url "prueba.json " devolver utf-8 codificado respuesta?

Aquí está el código para el servicio:

@Stateless
@Path("/")
public class RestTest {   
    @EJB
    private MyDao myDao;

    @Path("test.xml/")
    @GET
    @Produces(MediaType.APPLICATION_XML )
    public List<Profile> getProfiles() {    
        return myDao.getProfilesForWeb();
    }

    @Path("test.json/")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<Profile> getProfilesAsJson() {
        return myDao.getProfilesForWeb();
    }
}

Este es el pojo que utiliza el servicio:

package se.kc.mimee.profile.model;

@XmlRootElement
public class Profile {
    public int id;
    public String name;

    public Profile(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public Profile() {}

}
Author: Jojje, 2012-02-20

7 answers

Jersey siempre debe producir utf-8 de forma predeterminada, parece que el problema es que su cliente no lo está interpretando correctamente (la declaración xml no lo "convierte" en utf-8, solo le dice al cliente cómo analizarlo).

¿Con qué cliente está viendo estos problemas?

Se supone que JSON válido solo es Unicode (utf-8/16/32); los analizadores deberían ser capaces de detectar la codificación automáticamente (por supuesto, algunos no lo hacen), por lo que no hay ninguna declaración de codificación en JSON.

Puedes añadirlo para el Content-Type así:

@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")
 90
Author: Dmitri,
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-10 22:17:26

Si agregar el conjunto de caracteres a todos y cada uno de los recursos no es una opción, tal vez la respuesta a esta pregunta, que muestra cómo hacer cumplir un conjunto de caracteres predeterminado, podría ser útil.

 5
Author: martin,
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:10:30

responseMessage es la clase bean en la que podemos enviar UTF-8 charset en respuesta.

return Response.ok(responseMessage).header("Content-Type", "application/json;charset=UTF-8").build();
 3
Author: Prem Kumar,
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
2016-03-29 05:57:30

If @Produces(MediaType.APPLICATION_JSON+"; charset = utf-8") no funciona, entonces intente:

@ Produce ("application/json;charset=utf-8")

En teoría es lo mismo, pero la primera opción no me funcionó

 3
Author: JACA,
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
2016-05-19 05:27:29

También puedes probar esto:

return Response.ok(responseMessage, "application/json;charset=UTF-8").build();
 0
Author: K.Alianne,
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-07-01 21:37:12

Jersey tiene errores, cuando se usa Content-Type application/json, no detecta la codificación JSON unicode automáticamente como se supone que debe, pero deserializa el cuerpo de la solicitud con cualquier codificación de plataforma de tiempo de ejecución utilizada por su servidor. Lo mismo se aplica a la serialización del cuerpo de respuesta.

Su cliente necesita especificar explícitamente el conjunto de caracteres UTF-8:

Content-Type: application/json;charset=utf-8
 0
Author: Dušan Zahoranský,
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
2018-02-07 01:41:05

Tengo el mismo problema en servlet

Utilice amablemente: resp.setContentType ("application / json; charset = utf-8");

public static void flashOutput(HttpServletRequest req
            , HttpServletResponse resp
            , String output) {

        try {

            Utils.print2("output flash"+output);

            resp.setContentType("application/json;charset=utf-8");
            PrintWriter pw = resp.getWriter();
            pw.write( new String(output.getBytes("UTF-8")));
            pw.close();
            resp.flushBuffer();

        } catch (Exception e) {
            // TODO: handle exception
        }

    }// end flashOutput
 0
Author: Vinod Joshi,
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
2018-09-19 07:33:27