JSON front and back transmission, and garbled Chinese problem discussion

Source: Internet
Author: User

Background introduction:

My current job is to do traditional project development, not to use the framework. In recent projects, it is often necessary to use Ajax to get data from the background to the foreground, in JSON format. First of all, I encountered problems in the project, the front desk to get the data, need to convert it to objects, I use the jquery plugin with the Jquery.parsejson () This method, no effect, using the browser comes with the Json.parse (str) is also no effect, Through the search to know, this method for IE browser support is not good, the current support is IE8 (non-compatible mode), IE9, and so on, and so on the version, do the traditional development should know that the browser can only use IE, helpless through the access to know, to use this method, you need to import a json.js, Can be downloaded from GitHub, address: https://github.com/douglascrockford/JSON-js, import json2.js into your project is good. I'm not using this method, I'm using the eval function of JS. How to use:

function test3 () {    var json = ' {' name ': ' John Doe ', ' age ': ' + '} ';     var $json = eval ("(" +json+ ")");    Alert (typeof($json)); // Object    Alert ($json. Name); // John Doe }

The small example above demonstrates how eval is used. Let's take a look at how the project for the SSM architecture is transmitted using the JSON data format!

Premise: Mastering the conversion of JSON objects and JSON strings;

JSON object--"JSON string:

Json.stringify (JSON object);

JSON string-—— "JSON object

Eval ("(" +json string + ")") function, $.parsejson (JSON string), Jquery.parsejson (JSON string), Json.parse (JSON string);

For JSON objects, take a value, just the. Attribute is available.

First, the front desk to accept the background transmission of JSON data garbled problem

Background: Using the SSM framework

Background:

1@RequestMapping ("/test1")2 @ResponseBody3      Publicresultinfo test1 (httpservletresponse response) {4Resultinfo result =Newresultinfo ();5Result.setcode ("200");6Result.setdesc ("The request was successful! ");7map<string,string> map =NewHashmap<string,string>();8Map.put ("name", "Precipitant");9Map.put ("Age", "35");Ten result.setdata (map); One         returnresult; A}

Front desk:

1 function Test1 () {2 $.ajax ({3Type: ' Post ',4URL: ' Json/test1 ',5DataType: ' Josn ',6 success:function (text) {7var code =Text.code;8var desc =Text.desc;9Alert (code+desc);Tenvar obj =Text.data; OneAlert (Obj.name +obj.age); Avar str =json.stringify (text); - alert (str); -         }, the error:function (data) { -Alert ("exception occurs in the background, please contact the Administrator!") "); -         }, -Asyn:false, +Cachefalse -     }); +}

At this time there is no garbled, but sometimes our reception accepts the type of text is sometimes JSON objects, sometimes JSON type of string, how to accurately determine what type of data we get from the background? Let's not talk about it here.

Look at the second example of

Background:

1@RequestMapping (value= "/test2"/*, produces= "Text/html;charset=utf-8"*/)2 @ResponseBody3      PublicString test2 (httpservletresponse response) {4Resultinfo result =Newresultinfo ();5Result.setcode ("200");6Result.setdesc ("The request was successful! ");7map<string,string> map =NewHashmap<string,string>();8Map.put ("name", "Crimson");9Map.put ("Age", "22");Ten result.setdata (map); OneString str =jsonobject.tojsonstring (result); A System.out.println (str); -         returnstr; -}

Front desk:

1 function Test2 () {2 $.ajax ({3Type: ' Post ',4URL: ' Json/test2 ',5DataType: ' JSON ',6 success:function (text) {7 alert (text);8Alert (text.code+text.desc);9         },Ten error:function (text) { OneAlert ("exception occurs in the background!") "); A         }, -Asyn:false, -Cachefalse  the     }); -}

At this time the foreground has been garbled, even if it is set up response.setcharacterencoding ("Utf-8"); Response.setcontenttype ("Application/json;charset=utf-8");

These two words also do not work, if this set: @RequestMapping (value= "/test2", produces= "Text/html;charset=utf-8") at this time is not garbled. At this time should be able to solve all the problems encountered by all Chinese characters!

In fact, in the final analysis is the message converter in Mischief!!!

In fact, we can open the character message converter to view the next. You can see that the default encoding of the string converter is iso-8859-1

1  Public classStringhttpmessageconverterextendsAbstracthttpmessageconverter<string> {2 3      Public Static FinalCharset default_charset = Charset.forname ("Iso-8859-1");4 5 6     Private FinalList<charset>availablecharsets;7 8     Private BooleanWriteacceptcharset =true;

Backstage test1: Go is mappingjackson2httpmessageconverter this converter, directly to transfer the object back to the foreground.

Backstage test2: Go to stringhttpmessageconverter this converter, and then encode the string with iso-8859-1.

Nature will appear garbled.

We can encode the message converter by customizing it as follows:

1 <Mvc:annotation-driven>2         <mvc:message-convertersRegister-defaults= "true">3             <Beanclass= "Org.springframework.http.converter.StringHttpMessageConverter" >4             < Propertyname= "Supportedmediatypes">5                 <List>6                     <value>Application/json;charset=utf-8</value>7                     <value>Text/html;charset=utf-8</value>8                      <!--application can be found in any Form form Enctype property by default -  9                     <value>application/x-www-form-urlencoded</value>  Ten                 </List> One             </ Property> A             </Bean> -             <Beanclass= "Org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" > -             </Bean> the         </mvc:message-converters> -     </Mvc:annotation-driven>

In the process, I found an interesting place, for Test2 (), if put text/html in front, back to the foreground is a string JSON string, if put application in front, back to the foreground is JSON object, actually not difficult to understand,

When walking Stringhttpmessageconverter This converter, will take this converter inside the supported data type and the request header acceptable data type comparison, is the request header inside the accept, if compared to success, it is no longer than the next, So this can be a pinch of the front desk to get the data is what type.

Summary below:

There are two ways to do this without garbled.

First: In the Annotated @requestmapping () Add: produces= "Text/html;charset=utf-8"

Second: Configure the specified encoding on the message converter.

JSON front and back transmission, and garbled Chinese problem discussion

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.