1

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.

Alex_P
  • 2,580
  • 3
  • 22
  • 37
  • `var jobj = JObject.Parse(json);` would convert it to a JObject. I would not try to bring powershell into C# and start looking into method and processes that C# gives you to "serialize" and "deserialize" the json object/string – Jawad Feb 26 '20 at 14:05
  • Did you ever get an answer? – bob Sep 07 '22 at 17:31
  • @bob, I believe I eventually used some version of Jawad's first options. It is however suboptimal as the Json objects were dynamic so the classes didn't match and the deserialization failed occasionally. – Alex_P Sep 08 '22 at 07:32

1 Answers1

0

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.
Jawad
  • 11,028
  • 3
  • 24
  • 37