Using JSON in automation

9 years 3 months ago #1993 by medyk8ns
Hi,
I would like to get some data from weather api in my automation program. Data received from service is in JSON format.
Is it possible to add Newtonsoft.Json assembly to automation program, so I can use it like this:
var client = new System.Net.WebClient();
var jsonString = client.DownloadString("apiurl");
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(jsonString);
var qpf = double.Parse(result .forecast.simpleforecast.forecastday[0].qpf_allday.mm.Value);

For now I am parsing JSON as string, which is fine, but if Newtonsoft.Json.dll is in solution already, it would be handy to use it.
The following user(s) said Thank You: NightOne

Please Log in or Create an account to join the conversation.

9 years 3 months ago #2011 by medyk8ns
Replied by medyk8ns on topic Using JSON in automation
So answering my own topic:
It is possible to use reflection to do so.

First lets add a property for method info(it loads assembly and finds DeserializeMethod):
private System.Reflection.MethodInfo _deserializeObjectMethodInfo;
public System.Reflection.MethodInfo DeserializeObjectMethodInfo
{
    get
    {
        if (_deserializeObjectMethodInfo == null)
        {
            var assembly = System.Reflection.Assembly.LoadFrom("Newtonsoft.Json.dll");          
            var jobjectType = assembly.GetType("Newtonsoft.Json.JsonConvert");
            _deserializeObjectMethodInfo = jobjectType.GetMethods().SingleOrDefault(m => m.Name == "DeserializeObject" && !m.IsGenericMethod && m.ReturnType==typeof(object) && m.GetParameters().Count()==1);  
          	//can also use Parse method from JObject
               //var jobjectType = assembly.GetType("Newtonsoft.Json.Linq.JObject");
               //_deserializeObjectMethodInfo= jobjectType.GetMethod("Parse");               
        }
        return _deserializeObjectMethodInfo;
    }
}

then just call Invoke:
dynamic dynObj = DeserializeObjectMethodInfo.Invoke(this, new object[] { jsonString });
The following user(s) said Thank You: NightOne

Please Log in or Create an account to join the conversation.

Time to create page: 0.327 seconds

Forum latest

  • No posts to display.