【问题标题】:Run c# function with Powershell does not recognize JObject使用 Powershell 运行 c# 函数无法识别 JObject
【发布时间】:2021-01-13 03:31:34
【问题描述】:

我正在 Powershell 上编写一个运行 C# 类的脚本,在该类中我得到一个表示 JSON 的字符串(通过 REST API)。 我已经验证了来自请求的响应字符串是有效的,但是当我尝试使用 using Newtonsoft.Json; 将其解析为 JSON 时,我收到了无法识别 JObject 的错误。

我的 Powershell 脚本:

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

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

$basicTestObject.doForecast()

我的 C# 代码:

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);
            ...
        }

错误是:

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

我还尝试添加using Newtonsoft.Json.Linq;,但没有成功。

我做错了什么?

【问题讨论】:

  • 使用 Newtonsoft.Json.Linq 是必需的,因为这是 JObject 所在的位置。添加它,重建 WeatherForecast 程序集并在 powershell 中重试。
  • 添加后出现以下错误:“System.Object”类型是在未引用的程序集中定义的。您必须添加对程序集 'netstandard, Version=2.0.0.0, Culture=neutral, 的引用
  • 我假设您的 C# 代码构建正常。那么powershell脚本肯定有问题。您可以在这里发布您的完整脚本吗?

标签: c# json powershell json.net


【解决方案1】:

您的代码不遵循 a Minimal, Reproducible example尤其是我们谈论的是什么版本的 C#、.NET Framework/Core、PowerShell)但我想您知道程序集是如何加载的在 PowerShell 中都错了。

以下是如何正确执行此操作的示例。研究它并相应地调整您的程序。

C# 代码(.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; }
    }

}

测试文件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 执行

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

$serviceProgram = New-Object "Test.Program"
$serviceProgram.DisplayService()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-05-26
    • 2018-10-10
    • 2015-08-16
    • 1970-01-01
    • 2018-06-05
    • 2014-07-08
    • 2021-05-23
    • 2012-12-10
    相关资源
    最近更新 更多