C # convert json to a dynamic object, and then dynamically obtain the value in the specified string list in the dynamic object,
Using Newtonsoft. Json;
Using System;
Using System. Collections. Generic;
Using System. Linq;
Using System. Text;
Using System. Threading. Tasks;
Namespace ConsoleApp1
{
Class Program
{
Static void Main (string [] args)
{
String ss = TestAA ();
Console. WriteLine (ss );
Console. ReadKey ();
}
Private static string TestAA ()
{
String allowAttr = string. Empty;
String json = "{\" UserName \ ": \" Jack \ ", \" LoS \ ": \" Beijing \ ", \" Group \": \ "34 \"}";
// Simulate returning json to a dynamic object without creating an object class.
Var DynamicObject = JsonConvert. DeserializeObject <dynamic> (json );
// Var _ value = DynamicObject ["LoS"];
List <string> ssList = new List <string> ();
SsList. Add ("LoS ");
SsList. Add ("Test2 ");
Foreach (string item in ssList)
{
Var value2 = DynamicObject [item]; // obtain the field in the string list dynamically and find the value of the corresponding field in the dynamic object.
If (value2! = Null)
{
AllowAttr = string. Format ("{0} {1}", value2, "_ Attribute ");
// String allowAttr2 = string. Format ("{0} {1}", value2.Value, "_ Attribute ");
}
}
Return allowAttr;
// Console. WriteLine (DynamicObject. LoS );
// Type Ts = DynamicObject. GetType ();
// Object o = Ts. GetProperty ("Name"). GetValue (DynamicObject, null );
// String Value = Convert. ToString (o );
// If (string. IsNullOrEmpty (Value ))
//{
// Return null;
//}
// Else
//{
// Return Value;
//}
}
}
}