Dynamic dynamic type T to a specific type of program

Original: Dynamic dynamic type T to a specific type of program

Demand scenario: Sometimes we caught some request data, string data in JSON format, needs to be placed in the interface to reproduce the problem, we may accept data with dynamic, then converted to a request specific data.

 

Option One: Direct use of a specific object T, to accept the requested data, can not it? Sure, but when JSON data includes sub-objects, I encountered the problem of missing child data objects. If you do not encounter, it can be used.

 

Option Two: Use string to accept the string data in JSON format and then deserialized into an object, but this you will need to deal with string, backslash, if you took the trouble, can be used.

 

Option Three: My personal recommendation: Use dynamic data type to accept, and then converted to T objects, more convenient and practical, is the key to the code below:

Ideas: Use dynamic.ToString () method, obtained Json string, then deserialize method, a scheme to avoid data loss problems. Easy to use! ! ! recommend! ! !

 

///  <Summary> 
        ///   analog request
         ///  </ Summary> 
        ///  <param name = "fromBody"> receives the response value after encryption result </ param> 
        ///  <Returns> After obtaining decrypting the value returned in response to the result </ returns> 
        [HttpPost]
         public HttpResponseMessage the Test ( Dynamic fromBody) // Dynamic a JObject 
        {
             String a = fromBody.ToString ();
            T t=  Newtonsoft.Json.JsonConvert.DeserializeObject<T>(a);

            return result;
        }

 

Guess you like

Origin www.cnblogs.com/lonelyxmas/p/11100206.html