Search code examples
c#jsonserializationjson.net

Can I get a property by its property name, if this is already defined in "[JsonProperty]"?


I'm working on a C# program for JSON serialisation.

My object looks as follows (example of a property):

public class Device
{
    [JsonProperty("ALLTYPES_NAME")]
    public string ALLTYPES_NAME { get; set; }
    [JsonProperty("INFORMATION")]
    public string INFORMATION { get; set; }
    ...

Now I have the following information (in a textfile):

ALLTYPES_NAME  "Object1"
ALLTYPES_NAME  "Object2"
INFORMATION    "Inside_Info"

I would like to create two objects, which are to be JSON serialised as follows:

"desired_objects": [
{
  "ALLTYPES_NAME": "Object1",
},
{
  "ALLTYPES_NAME": "Object2",
  "INFORMATION": "Inside_Info,
  ...

In order to get this done, I need something like:

temp_obj.GetPropertyByName("ALLTYPES_NAME") = "Object1";
desired_objects.Add(temp_obj);
...
temp_obj.GetPropertyByName("ALLTYPES_NAME") = "Object2";
temp_obj.GetPropertyByName("INFORMATION")   = "Inside_Information";
...

One way to do this, is working with templates. However I wonder if this is needed, seen the fact that the needed information is retrievable using the [JsonProperty] directives, hence my question:

Does a method .GetPropertyByName() exist, based on the [JsonProperty ...]? (Or even larger, can the [JsonProperty] directives be used for something else rather than the JSON serialiser?)


Solution

  • After some experiments, based on the comments of Jon Skeet, I realise that I don't even need the JSON directives for this, as you can see from following code excerpt:

    System.Reflection.PropertyInfo[] list_of_attributes = 
      (new Own_Class()).GetType().GetProperties();
    string[] list_of_attribute_names = new string[list_of_attributes.Length];
    for (int i = 0; i< list_of_attributes.Length; i++)
      list_of_attribute_names[i] = list_of_attributes[i].Name;
    combobox_on_form.Items.AddRange(list_of_attribute_names);