Application of dynamic type and anonymous type in ASP. Webapi

Source: Internet
Author: User

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

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.