spring mvc jquery ajax response as json encoding i

2019-08-01 12:49发布

问题:

Recenlty I have big problem with Polish Characters in JSON response from the server. I have simple Ajax request for this:

jQuery.ajax( "/GetSimpleRuleList",
    {
        type:"GET",
        responseType:"application/json;charset=utf-8",
        contentType:"application/json;charset=utf-8",
        cache:false
    } ).done( function ( data )
    {
        console.log( data );
        //nevermind here
    } );

And appropriate Controller at server end:

@RequestMapping(value = "/GetSimpleRuleList", method = RequestMethod.GET)
public
@ResponseBody
String getRuleList( ServletResponse response )
{
    //magically getting my list here
     response.setCharacterEncoding( "UTF-8" );
    return //Using JACKSON ObjectWriter here
}

Now I'm 100% sure that encoidng on server side and database from where I take data from is OK, no problem with that. But when It comes to reading response from server it is:

???

instead of Polish char like:

ąćź

Moreover it only fails when receiving response from server, while sending a request with data is encoded correctly.

In my web.xml I have filter for character encoding.

Any help with this? I'm out of ideas.

回答1:

Now I'm 100% sure that encoidng on server side and database from where I take data from is OK

try adding the Content-Type header if it's not already present int your response:

response.setHeader("Content-Type", "application/json;charset=UTF-8")

Get sure to use UTF-8 charset when reading from database. Jackson's encoding defaults to UTF-8, so your data might not be encoded using UTF-8?!?

what encoding do you use when reading from database? maybe ISO-8859-2?



回答2:

Try changing your response type to org.springframework.http.ResponseEntity

public ResponseEntity<String> getRuleList(){
    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json; charset=utf-8");
    responseHeaders.setCacheControl("no-cache, max-age=0"); 
    String allyourjson = "yourjsongoeshere";
    return new ResponseEntity<String>(allyourjson, responseHeaders, HttpStatus.OK);
}


回答3:

You can use spring annotation RequestMapping above controller class for receveing application/json;utf-8 in all responses

@Controller
@RequestMapping(produces = {"application/json; charset=UTF-8","*/*;charset=UTF-8"})
public class MyController{
 ...
@RequestMapping(value = "/GetSimpleRuleList", method = RequestMethod.GET)
public
@ResponseBody
String getRuleList( ServletResponse response )
{
    //magically getting my list here
     response.setCharacterEncoding( "UTF-8" );
    return //Using JACKSON ObjectWriter here
}
 ...
}