Method of reading json data in C using MSScriptControl

  • 2021-11-30 01:15:40
  • OfStack

JavaScriptSerializer classes already exist in C # to deserialize json data into objects


/// <summary>
/// JSON Text to object , Generic method 
/// </summary>
/// <typeparam name= " T " > Type </typeparam>
/// <param name= " jsonText " >JSON Text </param>
/// <returns> Object of the specified type </returns>
public static T JSONToObject<T>(string jsonText)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
return jss.Deserialize<T>(jsonText);
}
catch (Exception ex)
{
throw new Exception( " JSONHelper.JSONToObject():  "  + ex.Message);
}
}

But lazy people like me don't want to define a class in advance. I just want to parse the json data sent from the client directly, or use MSScriptControl. ScriptControl.

With the eval method, you can do whatever you want

//Build scriptcontrol to read json data passed by the client


MSScriptControl.ScriptControl sc = new MSScriptControl.ScriptControl();
sc.Language= " JScript " ;
sc.AddCode( " var jsonObject= " +data );//data For the submitted json Text 

Then you can use eval according to the structure of json, and write as you like in js.

Such as sc. Eval ("jsonObject. content. length")

sc. Eval ("jsonObject. itemValue")

To use MSScriptControl, you need to reference the com component Microsoft Script Control 1.0.


Related articles: