简体   繁体   中英

JAVA Rest services JSON encoding

I have a rest service which returns a list of Dto's one field in dto is localized and is translated to some countries, the problem is when i test it in soap UI i see that special characters are encoded from Kjøregodtgjørelse to Kjøregodtgjørelse here's the code snippet :

@Path("user")
@RequestScoped
@RolesAllowed(Roles.REGULAR_USER)
public class UserTravelRest extends RESTEndpoint<UserTravelService > {

    @EJB
    private UserTravelService service;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("travel")
    public List<TravelsDTO> getTravels() throws GeneralException {
        return service.getTravelsForUser();
    }

So it's just a simple get which returns dto list which looks like this :

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@XmlRootElement
public class TravelsDTO implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private BigDecimal amount;
    private String displayName;
}

displayName is the field which gets encoded. Should i add some unescaping before returning list in rest service or something else ?

您必须明确说明文本编码:

@Produces("application/json; charset=UTF-8")

There may be an issue with your client. According to the JSR 339 , UTF-8 should be used by default if no other charset is specified:

When writing responses, implementations SHOULD respect application-supplied character set metadata and SHOULD use UTF-8 if a character set is not specified by the application or if the application specifies a character set that is unsupported.

As already mentioned in diginoise's answer , to make sure that your resource method is producing UTF-8 encoded data, you can use:

@Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM