简体   繁体   中英

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

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.

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

        }

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.

只需在Properties上使用 LINQ

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

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