繁体   English   中英

如何将 JSON 字符串转换为 PSObject?

[英]How to convert a JSON string to PSObject?

我想用 C# 编写一个 PowerShell 函数。 在此过程中,我收到一个包含 JSON 内容的字符串。 我的示例 json 内容是:

string json = "{'TestNr':{'Name':'CSHARP', 'Description':'Test Descriptiopn'}}"

这个字符串应该像ConvertFrom-Json一样被转换为 PSObject。

我试图用下面的行创建一个对象。 它可以工作,但需要大量手动编写脚本,尤其是在 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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM