Home > other >  c# How to obtain the nth object property name in a dynamic object
c# How to obtain the nth object property name in a dynamic object

Time:07-07

I am trying to enumerate the NAMES of properties of JSON deserialised object.

dynamic x = data.elements[i];

Console.Write(x);

{{
  "order_type": "request",
  "order_id": "A511",
  "order_Date" : null,
  "order_name": "Preston",
}}

.GetProperties() will return the following:

Console.Write(x.GetType().GetProperties())

    [0]: {Newtonsoft.Json.Linq.JTokenType Type}
    [1]: {Newtonsoft.Json.Linq.JToken Item [System.Object]}
    [2]: {Newtonsoft.Json.Linq.JToken Item [System.String]}
    [3]: {Boolean HasValues}
    [4]: {Newtonsoft.Json.Linq.JToken First}
    [5]: {Newtonsoft.Json.Linq.JToken Last}
    [6]: {Int32 Count}
    [7]: {Newtonsoft.Json.Linq.JContainer Parent}
    [8]: {Newtonsoft.Json.Linq.JToken Root}
    [9]: {Newtonsoft.Json.Linq.JToken Next}
    [10]: {Newtonsoft.Json.Linq.JToken Previous}
    [11]: {System.String Path}

It has "First", and "Last". It has "Next" and "Previous". It even has "Parent".

But I need the name of the "nth" property. For instance, I need a reference to "order_date" in order to get it's name.

The goal here is to replace the null with empty string "". But I need a way of determining the name of the property that has that null.

If I am going about this completely wrong, and there is a better way to do this, I am open to correction.

CodePudding user response:

You can do the Where as Charlie's comment mentions, but if you need to iterate properties, this is one way.

public void DoWork()
        {
            string jsonString = @"
{
""order_type"": ""request"",
""order_id"": ""A511"",
""order_Date"" : null,
""order_name"": ""Preston"",
}
";
            JObject jObject = JObject.Parse(jsonString);
            foreach (KeyValuePair<string, JToken> pair in jObject)
            {
                string keyName = pair.Key;
                Console.WriteLine(keyName);
            }

        }

CodePudding user response:

For openers, I did figure out this:

TypeDescriptor.GetProperties(data.elements[i])[2].Name; // --> "order_date"

So, now I can for() each one and check for nulls.

Open to other/better solutions.

CodePudding user response:

Just use LINQ on the Properties

x.Properties.Where(j => j.Type == JTokenType.Null)
  • Related