Introduction
To use WebService to separate the client from the server, it is necessary to use a contract between the two. JSON data is the first choice for developers, with the advantage of being completely independent of the language. C # JavaScriptSerializer provides a good way to serialize and deserialize between JSON and object objects.
Interface design
The data transformation consists of JSON deserialization into object objects and object serialization into JSON data. In the project, there will be many instance objects, all need to use the serialize and deserialize methods to achieve data conversion, we can abstract an interface IDFC (data format conversion interface). Because we are not sure whether the data object that gets from the server is a single object or LIST<OBJECT>, the object that is serialized in the JSON string returned by the contract WebService is list<object> The client post to WebService parameter is also the value after serializing the list<object> into a JSON string.
The interface is designed as follows:
1 namespace PROJECTMSMGT_FCL 2 3 public interface IDFC 4 { 5 string Object2json (list<object> models); 6 string JSON); 8 9 }
Interface implementation
In the project, we will design a lot of model class, User, Order, Product, project, stock and so on, so for the actual needs of the project, we can implement interface IDFC for different objects.
The following is an implementation class of two objects:
1 namespacePROJECTMSMGT_FCL2 {3 Public classDFC_PROJECT:IDFC4 {5 Public StaticJavaScriptSerializer js =NewJavaScriptSerializer ();6 7 #regionIDFC Members8 9 Public stringObject2json (list<object>models)Ten { One returnJS. Serialize (models); A } - - PublicList<object> Json2object (stringJSON) the { -List<project> Objs = js. Deserialize<list<project>>(JSON); - -list<object> list =Newlist<Object>(); + foreach(varIteminchObjs) - { + list. ADD (item); A } at returnlist; - } - - #endregion - } -}
1 namespacePROJECTMSMGT_FCL2 {3 Public classDFC_USER:IDFC4 {5 Public StaticJavaScriptSerializer js =NewJavaScriptSerializer ();6 7 #regionIDFC Members8 9 Public stringObject2json (list<Object>models)Ten { One returnJS. Serialize (models); A } - - Publiclist<Object> Json2object (stringJSON) the { -List<user> Objs = js. Deserialize<list<user>>(JSON); - -list<object> list =Newlist<Object>(); + foreach(varIteminchObjs) - { + list. ADD (item); A } at returnlist; - } - - #endregion - } -}
Summarize
The design of the
Data transformation layer is relatively simple, and the main work of the Data transformation layer is to implement serialization and deserialization between JSON and data objects. Provides a secondary service for proxy layer proxies, serializes the data object parameters into a JSON string before invoking the Web service proxy method, and, after invocation, deserializes the JSON string returned by the Web service into a data object. This entire process is completed at the functional distribution layer dispatcher.