1

I have an object created by a json mapper function (using LitJson). It contains indexed properties.

I can iterate through the properties and get each property value like this

for(int i = 0; i < jdata.Count;i++) {
    Console.WriteLine(jdata[i]);
} 

I would like to get each property name, as a string, rather than the property value.

The closest thing I've found is this https://stackoverflow.com/questions/1011109/how-do-you-get-the-name-of-the-property

Where this works

string name = ReflectionUtility.GetPropertyName((Sample2 s) => s.Foo);

but this doesn't (seemingly because it's an indexed property?)

string name = ReflectionUtility.GetPropertyName((Sample2 s) => s[0]);
Community
  • 1
  • 1
Spacecliff
  • 13
  • 4
  • I have no idea what "JsonLit" is, but most mainstream JSON parsers let you get the results back as a `Dictionary`, which of course makes doing what you want childs-play. – Kirk Woll Jun 13 '12 at 00:49
  • 2
    In a general answer to your question there is not such way to find index name based on index number. There is no relationship between index number or index name. Although best practices may sugesst to not doing so, but a programmer may implement indexing in a way that does not follow the indexing concept. The fact is that indexer actually can be seen as a function which only has one parameter. – 000 Jun 13 '12 at 00:52
  • 1
    What data type is `jdata` and what type does `jdata[]` return? – CodingWithSpike Jun 13 '12 at 00:53
  • @KirkWoll Thanks and yes, I can do that, however in the particular situation I have I still want to be able to get a property name from an index number on an indexed property. – Spacecliff Jun 13 '12 at 00:56
  • @rally25rs jdata is of a JsonData type, which is a type containing indexed properties returned by a JsonLit function that parses a JSON string. – Spacecliff Jun 13 '12 at 01:00
  • If you are depending on the logical order of the properties within the JSON stream, you are not using JSON correctly. – Kirk Woll Jun 13 '12 at 01:18
  • What is "JsonLit" and where did you get it? Google turns up nothing... – CodingWithSpike Jun 13 '12 at 01:32
  • @rally25rs whoops sorry is LitJson http://litjson.sourceforge.net/ – Spacecliff Jun 13 '12 at 01:37

2 Answers2

2

I found I had to cast the JsonData to an IDictionary before I could access the Keys property.

Like So:

JsonData x = getMyData();//however you're getting your JsonData object
var keys = (x as IDictionary).Keys; // you should probably check for null 
foreach(string s in keys)
   Console.WriteLine("Another key: "+s);
eternal512
  • 31
  • 3
1

I found the source code. Looks like JsonData implements IDictionary, so you should be able to access the Keys property.

Indexers are implemented basically as functions which take an index argument, so there's no way to use reflection to get a "Name" associated with a given index.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272