gp2gp2
gp2gp2

Reputation: 203

Get properties names from dynamic JSON in C# and later use those properties in foreach loop

I have below json response (I shortened it to just two records for purpose of this question):

[{"Container_Type":"0000CART","Standard_Tare_Weight":1.0,"Container_Type_Key":21363,"Description":"CARTON BOX","Container_Type_Description":"0000CART-CARTON BOX","Default":false,"Standard_Quantity":0.0,"Master_Unit_Type_Key":null,"Master_Unit_Type":"","Standard_Pack_Display":false,"Production_Quantity_Default":false},{"Container_Type":"0000PCTN","Standard_Tare_Weight":35.0,"Container_Type_Key":21375,"Description":"RETURNABLE CONTAINER","Container_Type_Description":"0000PCTN-RETURNABLE CONTAINER","Default":false,"Standard_Quantity":0.0,"Master_Unit_Type_Key":null,"Master_Unit_Type":"","Standard_Pack_Display":false,"Production_Quantity_Default":false}]

stored in dynamic json in c# code.

I wanted to get above keys like "Container_Type","Standard_Tare_Weight", etc to be populated to separate list so I created:

PropertyInfo[] dynamicProperties;
dynamicProperties = json.GetType().GetProperties();

How to write below foreach to return those properties?

foreach (var property in dynamicProperties)
{
    property.Name
}

Doesn't return "Container_Type","Standard_Tare_Weight", etc but instead:

Type    Item    Item    IsReadOnly  HasValues   First   Last    Count   Parent  Root    Next    Previous    Path

When I loop via this json and if I type the name of property "Container_Type":

foreach (var item in json)
{
    item.Container_Type
}

It shows proper values "0000CART" and "0000PCTN". So I know that those properties exist in that json object but how I can get them dynamically from that json object?

Assume I have this completed, how can I modify above foreach loop so it takes those properties names from my list of properties?

Maybe my reasoning is wrong and there are better ways to work with json objects in c#. I just want some flexible way to handle any json response and convert it on the fly without the need of creating model/class with the need of knowing properties names prior to getting the response.

Can you point me in correct direction?

Upvotes: 0

Views: 1814

Answers (1)

Guru Stron
Guru Stron

Reputation: 142243

Using Newtonsoft's Json.Net you can do the following:

var jarr = JArray.Parse(json); // or JsonConvert.DeserializeObject<JArray>(json);

foreach (var prop in jarr.First.Children().OfType<JProperty>())
{
    Console.WriteLine(prop.Name);
}

//// OR
//foreach (var prop in ((JObject)(jarr.First)).Properties())
//{
//  Console.WriteLine(prop.Name);
//}

foreach(JObject jObj in jarr)
{
    Console.WriteLine(jObj["Container_Type"]);
}

Or just to output properties you can do:

foreach(JObject jObj in jarr)
{
    foreach (var prop in jObj.Properties())
    {
        Console.WriteLine($"{prop.Path}-{prop.Name}-{prop.Value.ToString()}");
    }
}

Upvotes: 1

Related Questions