首页 > 解决方案 > 如何将 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#jsonpsobject

解决方案


有两种方法可以在 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.

推荐阅读