【发布时间】: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