简体   繁体   中英

How to convert a JSON string to PSObject?

I want to write a PowerShell function in C#. During the process I receive a string with JSON content. My sample json content is:

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

This string should be converted to a PSObject just like ConvertFrom-Json would do.

I was trying to create an object with below lines. It works but it would require a lot of manual scripting especially if the JSON string becomes longer.

PSObject obj = new PSObject();
obj.Properties.Add(new PSNoteProperty("Head", "Children"));

I tried also the below line:

obj = (PSObject)TypeDescriptor.GetConverter(typeof(PSObject)).ConvertFromString(json);

For this I get however the error (I run the function in PowerShell 7):

TypeConverter cannot convert from System.String.

There are two ways you can parse the string in C# that would be the easiest to go with.

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);

This is with the strong typed class object. This is what you should be using in C#.

Other way is to get an object

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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