Deserialization of JSON strings into JSON anonymous objects using JSON. net

Source: Internet
Author: User
First, define an anonymous object and serialize it to JSON for testing. How can I convert this josn string to a JSON object? If you create a class first, it will be too tired. VaR O = New
{
A = 1 ,
B = " Hello, world! " ,
C = New [] { 1 , 2 , 3 },
D = New Dictionary < String , Int > {{ " X " , 1 },{ " Y " , 2 }}
};

VaRJSON = jsonconvert. serializeobject (O );

First approach (Anonymous class ):

VaR Anonymous = New {A = 0 , B = string. Empty, c = New Int [ 0 ], D = New Dictionary < String , Int > ()};
VaR O2 = jsonconvert. deserializeanonymoustype (JSON, anonymous );

Console. writeline (o2. B );
Console. writeline (o2.c [1]);

 

Method 2 (anonymous ):

 

VaR O3 = jsonconvert. deserializeanonymoustype (JSON, New {C = New Int [ 0 ], D = New Dictionary < String , Int > ()});
Console. writeline (o3.d [ " Y " ]);

Deserializeanonymoustype only uses the reflection type of this anonymous object parameter (anonymous), that is, it is not the same object as the deserialization result. As with O3, we can also extract only local information.

 

Method 3 (Indexer ):

 

In fact, we can also directly deserialize it to jobject and then directly access it through the indexer. Jobject and jproperty all inherit from jtoken. It reloads the primitive type conversion operator and we can get the actual result directly.

VaR O2 = jsonconvert. deserializeobject (JSON) As Jobject;

Console. writeline ((Int) O2 ["A"]);
Console. writeline ((String) O2 ["B"]);
Console. writeline (O2 ["C"]. Values (). Count ());
Console. writeline ((Int) O2 ["D"] ["Y"]);

 

 

Self: http://fanhuayi.blog.163.com/blog/static/397789201142651336395/

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.