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/