简体   繁体   中英

How to Deserialize Json string to Type without creating class

I have an Json string.I would like to know how to Deserialize "Type" from Json string "without creating class".Please check my below code and advise how to do this....

string MParam = @"[{'ColCode': 'BK'}]";
object result = JsonConvert.DeserializeObject(MParam);

you can use 'dynamic' type

        string MParam = @"[{'ColCode': 'BK'}]";
        dynamic result = JsonConvert.DeserializeObject<dynamic>(MParam);
        var ColCode = result[0].ColCode;

you can do like this, i have done two way for this, but i would like to use second one.

string MParam = @"[{'ColCode': 'BK'}]";
var jsonArray = (JArray)JsonConvert.DeserializeObject(MParam);
var jo = (JObject)jsonArray[0];
Console.WriteLine(jo["ColCode"]);

and this next way is useful in many other places too, which uses anonymous

string MParam = @"[{'ColCode': 'BK'}]";
var colCodeDef = new[] { new { ColCode = "" } };
var myType = JsonConvert.DeserializeAnonymousType(MParam, colCodeDef);
var ColCodeData = myType[0].ColCode;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM