Summary of some problems in using JSON for data transmission format _ json

Source: Internet
Author: User
Json occupies a certain position in Web data processing by virtue of its own advantages. During this time, three projects were involved that use Json as the data transmission format, some of the pages use the Json data transmission format. Here I will summarize some of the problems with this method during this period and summarize the methods for providing JSON data to the client.
I. use WCF to provide Json data
When using WCF to provide Json data to the client, note that,
A. Define the contract. Set ResponseFormat in WebInvokeAttribute or WebGetAttribute to WebMessageForm. Json,

The Code is as follows:


[WebInvoke (Method = "POST", ResponseFormat = WebMessageFormat. Json, RequestFormat = WebMessageFormat. Json, BodyStyle = WebMessageBodyStyle. Bare)]
[WebGet (ResponseFormat = WebMessageFormat. Json, UriTemplate = "IsExistSSID/{SSID}", RequestFormat = WebMessageFormat. Json, BodyStyle = WebMessageBodyStyle. Bare)]


B. EndPointBehavior use WebHttp

The Code is as follows:







C. Use webHttpBinding in Binding mode

The Code is as follows:



Binding = "webHttpBinding" contract = "DeviceUIServiceContract"/>


Ii. Use. Net MVC Action to provide JSON data
1. in ValueProviderFactories. factories. add (new JsonValueProviderFactory () to process Json data. By default, MVC 3 is added. If MVC3 is used, ignore this.
2. Use JsonResult as the return value of your Action.
3. return Json (XXX); XXX indicates the data to be returned. The data type must be serializable.
3. It can be implemented using a simple WebService with the suffix asmx,
4. Implement it using the HttpHandler mechanism.
Since WCF has been defined by Microsoft as a communication platform in the Microsoft system, the latter two methods can be implemented as needed, but they are earlier implementation methods, so here I use WCF, directly regard the provided data as the interface provided by the system data.
While in. in the. net mvc environment, Json data can be directly output. in the. net mvc environment. net mvc environment is directly supported by JSON Action.
WEB Client Processing
Processing with JQuery Ajax
Set ype to 'json' format. When receiving data, the result is automatically converted to json object format.

The Code is as follows:


$. Ajax ({
Url: 'urladdress'
Type: 'get ',
ContentType: 'application/json ',
DataType: 'json ',
Cache: false,
Async: false,
Error: JQueryAjaxErrorHandler,
Success: function (result ){}
});


Exception Handling considerations

Here I mainly consider how to handle exceptions in the Web environment. According to the definition of the HTTP protocol, an HTTP Status Code is returned for each request. Different codes indicate different meanings. Therefore, our Web application should return different HTTP Status codes based on different results, such as 200, which indicates that the server returns the correct result and 417 indicates that the server is abnormal, 404. The request does not exist, and 301 is unauthorized.

In the WCF environment, we must first add FaultContract to each method, as shown below:
FaultContract (typeof (WebFaultException ))
Next, we need to handle the exception so that the server can return the correct HTTP Status Code.

The Code is as follows:


Try
{
// BussinessCode .....
}
Catch (DuplicateException ex)
{
Throw new WebFaultJsonFormatException (New WebErrorDetail (ex. Message, ex), HttpStatusCode. ExpectationFailed );
}
Catch (NotExistException ex)
{
Throw new WebFaultJsonFormatException (New WebErrorDetail (ex. Message, ex), HttpStatusCode. ExpectationFailed );
}
Catch (AppException ex)
{
Throw new WebFaultJsonFormatException (New WebErrorDetail (ex. Message, ex), HttpStatusCode. ExpectationFailed );
}
Catch (Exception ex)
{
Throw new WebFaultJsonFormatException (New WebErrorDetail (ex. Message, ex), HttpStatusCode. ExpectationFailed );
}
The signature of WebFaultJsonFormatException is as follows:
[Serializable, DataContract]
Public class WebFaultJsonFormatException : WebFaultException
{
Public WebFaultJsonFormatException (T detail, HttpStatusCode statusCode)
: Base (detail, statusCode)
{
ErrorDetailTypeValidator (detail );
}
Public WebFaultJsonFormatException (T detail, HttpStatusCode statusCode, IEnumerable KnownTypes)
: Base (detail, statusCode, knownTypes)
{
ErrorDetailTypeValidator (detail );
}
Private void ErrorDetailTypeValidator (T detail)
{
Foreach (DataContractAttribute item in detail. GetType (). GetCustomAttributes (typeof (DataContractAttribute), true ))
{
If (item. IsReference)
Throw new WebFaultJsonFormatException (New PureWebErrorDetail ("The DataContractAttribute property 'isrefer' which applied on {0} can't be true when the transfer code type is JSON fromat. ", typeof (T ). fullName), HttpStatusCode. expectationFailed );
}
}
}
[Serializable, DataContract (IsReference = false)]
Public class PureWebErrorDetail
{
Public PureWebErrorDetail (string message, params object [] args)
{
This. Message = string. Format (message, args );
}
[DataMemberAttribute]
Public string Message {get; set ;}
}


Because when JSON is used for data transmission, the IsReference in DataContract cannot be regarded as true, which means that, compared with XML, XML supports circular data reference, JSON is not supported. Therefore, WebFaultJsonFormatException is used to determine whether the IsReference of DataContract of the current JSON data type is true. If yes, a defined error message is returned. if this definition is not used, JQUery Ajax receives the HTTP Status Code 15 ??? But this error Code is not in our normal HTTP Status Code range.

A misunderstanding of Exception Handling
At the earliest time, I did not expect to use this method for processing, which was also a drawback of code writing for a long time. I added a fixed generic return value type to each method.

The Code is as follows:


[DataContract]
Public class TmResult
{
[DataMember]
Public bool Success {get; set ;}

[DataMember]
Public string ErrorMessage {get; set ;}

[DataMember]
Public string FullMessage {get; set ;}

[DataMember]
Public string CallStack {get; set ;}
}

[DataContract]
Public class TmResult : TmResult
Where T: class
{
[DataMember]
Public T Model {get; set ;}
}


Each time a Success is returned, it indicates whether the request is successful, and ErrorMessage indicates the error message in case of an error. In this way, the HTTP Status Code returned each time is 200, after knowing the solution above, I thought we didn't need to make it so complicated. Since it is Web, why didn't I write programs more in line with the HTTP Protocol definition, that's not easy.

Therefore, we have also learned the benefits of various standards, familiarized ourselves with standards, programming models, and various APIs. Our development will be simpler and easier.
The above are all written according to my personal understanding. please correct me if there is anything wrong with it.
Related Article

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.