1. Dynamic type for WEBAPI calls
Suppose you need to call a WEBAPI,WEBAPI to return a JSON string. The string is as follows:
{"ProductId": "AN002501", "ProductName": "xx detergent", "Description": "", "UnitPrice": 9.9}
Q: How do I get the values in a JSON string?
The general practice is to build a class before deserializing it with JsonConvert. Examples are as follows:
(1) Building classes
1 Public classProduct2 {3 4 Public stringProductId {Get;Set; }5 6 Public stringProductName {Get;Set; }7 8 Public stringDescription {Get;Set; }9 Ten Public decimalUnitPrice {Get;Set; } One A}
(2) Deserialization:
1 string " {\ "productid\": \ "an002501\", \ "productname\": \ "xx washing powder \", \ "description\": \ "\", \ "unitprice\": 9.9} " ; 2 3 Dynamic Product = jsonconvert.deserializeobject<product> (jsonstring);
If you use a dynamic type , you do not need to construct a class to host the serialization. Examples are as follows:
1 Dynamic obj = jsonconvert.deserializeobject<dynamic> (jsonstring);
2. Anonymous type for WEBAPI output
Suppose you need to output the following JSON string: {"Id": "AN002501", "Price": 9.9}. Q: How do I achieve my goal?
The general practice is to first build a class that has the ID and price property, and then serialize it and then output it. Examples are as follows:
(1) Building classes
1 Public class simpleproduct 2 {3 Public string Get Set ; } 4 5 Public decimal Get Set ; } 6 }
(2) Output after serialization
Public ActionResult Test1 () { return Json (new"1333"9.9M }, Jsonrequestbehavior.allowget);
}
If you use anonymous types , you do not need to construct a class to host serialization. Examples are as follows:
Public ActionResult Test2 () { return Json (new"1333"9.9M }, Jsonrequestbehavior.allowget);}
Application of dynamic type and anonymous type in ASP. Webapi