c# - 如何将 JSON 字符串转换为 PSObject?
问题描述
我想用 C# 编写一个 PowerShell 函数。在此过程中,我收到一个带有 JSON 内容的字符串。我的示例 json 内容是:
string json = "{'TestNr':{'Name':'CSHARP', 'Description':'Test Descriptiopn'}}"
这个字符串应该被转换为 PSObject 就像ConvertFrom-Json
会做的那样。
我试图用下面的线创建一个对象。它可以工作,但需要大量手动编写脚本,尤其是当 JSON 字符串变长时。
PSObject obj = new PSObject();
obj.Properties.Add(new PSNoteProperty("Head", "Children"));
我还尝试了以下行:
obj = (PSObject)TypeDescriptor.GetConverter(typeof(PSObject)).ConvertFromString(json);
为此,我得到了错误(我在 PowerShell 7 中运行该函数):
TypeConverter 无法从 System.String 转换。
解决方案
有两种方法可以在 C# 中解析字符串,这将是最容易使用的。
public class MyClass
{
public TestNRClass TestNR { get; set; }
}
public class TestNRClass
{
public string Name { get; set; }
public string Description { get; set; }
}
// In the main,
string json = @"{""TestNr"":{""Name"":""CSHARP"", ""Description"":""Test Descriptiopn""}}";
MyClass jobj = JsonConvert.DeserializeObject<MyClass>(json);
Console.WriteLine(jobj.TestNR.Name);
这与强类型类对象有关。这就是您应该在 C# 中使用的内容。
另一种方法是获取对象
string json = @"{""TestNr"":{""Name"":""CSHARP"", ""Description"":""Test Descriptiopn""}}";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj.ToString());
Console.WriteLine(obj["TestNr"]["Name"].ToString());
// You can also add more keyValuePair
obj["NewVariable"] = "stest";
Console.WriteLine(obj.ToString()); // Shows the new item as well.
推荐阅读
- email - 从我的域中的电子邮件帐户发送的电子邮件到达垃圾邮件
- laravel - 如何在 Laravel 中对下载文件名进行单元测试
- c# - 优雅地停止 ASP.NET Core Web App(从 Visual Studio 调试器中),一个与 IHostedService 相关的问题
- python - How do I send things that aren't strings with sockets? E.g taking a screenshot with the client and sending it to the server
- apache-flink - 生产者(kafka)不产生新行时如何让Flink刷新最后一行
- excel - 合并工作簿并验证重复项
- google-chrome - Chrome 开发工具:显示 cookie
- mysql - 在 where 子句中使用 if()
- ios - 编程不向给定电话号码发送验证码
- java - 我可以使用线程将消息发送到一个独特的 kafka 主题吗?如果是,如何?