[英]How to cast PSObject to SecureString. Cannot implicitly convert
[英]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.