0

I'm am writing a script at Powershell that is running a C# class, and within the class I am getting a string that represents a JSON (through REST API). I have verified that the response string from the request is valid, but when I am trying to parse it to JSON with using Newtonsoft.Json; I am getting an error that JObject is not recognized.

My Powershell script:

$referencingassemblies = ("Newtonsoft.Json.dll")
Add-Type -Path "WeatherForecast.cs" -ReferencedAssemblies $referencingassemblies

$basicTestObject = New-Object Forecast.WeatherForecast(...)

$basicTestObject.doForecast()

My C# code:

using Newtonsoft.Json;
...
        public string doForecast()
        {
            var dateTimeOffset = new DateTimeOffset(this.requiredDate);
            var unixDateTime = dateTimeOffset.ToUnixTimeSeconds();
            
            string apiCall = "http://api.openweathermap.org/data/2.5/onecall/timemachine?lat=" + this.latitude + "&lon=" + this.longitude + "&dt="+ unixDateTime.ToString() +"&units=metric&appid=" + API_KEY;
                
            // Create a web client.
            using (WebClient client = new WebClient())
            {
                // Get the response string from the URL.
                try
                {
                    getObservationResponse(client.DownloadString(apiCall));
                }
                catch (WebException ex)
                {
                    return ex.ToString();
                }
                catch (Exception ex)
                {
                    return ex.ToString();
                }
            }
            
            return "done";
        }

        private void getObservationResponse(string response)
        {
            JObject json = JObject.Parse(response);
            ...
        }

And the error is:

The type or namespace name 'Json' could not be found (are you
missing a using directive or an assembly reference?)

I also tried to add using Newtonsoft.Json.Linq; which didn't work.

What am I doing wrong?

3
  • using Newtonsoft.Json.Linq is required because that is where JObject resides. Add it ,rebuild WeatherForecast assembly and try again in powershell. Commented Sep 27, 2020 at 10:58
  • After adding it I get the following error: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, Commented Sep 27, 2020 at 14:04
  • I assume your C# code is building OK. There has to be some problem with powershell script then. Is it possible for you to post your full script here? Commented Sep 27, 2020 at 16:25

1 Answer 1

0

Your code does not follow a Minimal, Reproducible example (especially what version of C#, .NET Framework/Core, PowerShell are we talking about) but I guess you get the idea of how the assembly are loaded in PowerShell all wrong.

Here is an example how to do it properly. Study it and adjust your program accordingly.

C# code (.NET Core 3.1)

using System;
using System.IO;
using Newtonsoft.Json;

namespace Test
{
    public class Program
    {
        public void DisplayService()
        {
            var serviceList = JsonConvert.DeserializeObject<Service[]>(File.ReadAllText("Test.json"));
            foreach (var service in serviceList)
            {
                Console.WriteLine($"Service: {service.Name}");
            }
        }
    }


    public class ServiceList
    {
        public Service[] List { get; set; }
    }

    public class Service
    {
        public bool CanPauseAndContinue { get; set; }
        public bool CanShutdown { get; set; }
        public bool CanStop { get; set; }
        public string DisplayName { get; set; }
        public string[] DependentServices { get; set; }
        public string MachineName { get; set; }
        public string ServiceName { get; set; }
        public string[] ServicesDependedOn { get; set; }
        public object ServiceHandle { get; set; }
        public int Status { get; set; }
        public int ServiceType { get; set; }
        public int StartType { get; set; }
        public object Site { get; set; }
        public object Container { get; set; }
        public string Name { get; set; }
        public string[] RequiredServices { get; set; }
    }

}

Testing file Test.json

[
    {
        "CanPauseAndContinue":  false,
        "CanShutdown":  false,
        "CanStop":  false,
        "DisplayName":  "Agent Activation Runtime_71937",
        "DependentServices":  [

                              ],
        "MachineName":  ".",
        "ServiceName":  "AarSvc_71937",
        "ServicesDependedOn":  [

                               ],
        "ServiceHandle":  null,
        "Status":  1,
        "ServiceType":  224,
        "StartType":  3,
        "Site":  null,
        "Container":  null,
        "Name":  "AarSvc_71937",
        "RequiredServices":  [

                             ]
    },
    {
        "CanPauseAndContinue":  false,
        "CanShutdown":  false,
        "CanStop":  false,
        "DisplayName":  "Služba směrovače AllJoyn",
        "DependentServices":  [

                              ],
        "MachineName":  ".",
        "ServiceName":  "AJRouter",
        "ServicesDependedOn":  [

                               ],
        "ServiceHandle":  null,
        "Status":  1,
        "ServiceType":  32,
        "StartType":  3,
        "Site":  null,
        "Container":  null,
        "Name":  "AJRouter",
        "RequiredServices":  [

                             ]
    }
]

PowerShell execution

$AccType = Add-Type -AssemblyName "Test" -PassThru
# You may check what is inside $AccType

$serviceProgram = New-Object "Test.Program"
$serviceProgram.DisplayService()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.