Search code examples
c#json.net

Dynamic property name for serialization


I need to have a dynamic property-name for the serialization.

public class Home
{
    public virtual int Id { get; set; } // value: 2

    public virtual string propertyName { get; set; } // value: administration

    public virtual string Text { get; set; } // value: text1
} 

should serialize to:

{
  "Id": 2,
  "administration": "text1"
}

Is there any way to serialize that? Which is the best way to deserialize it?


Solution

  • Add a ToJObject method that returns a JObject.

    public JObject ToJObject()
    {
        JObject jObject = new JObject()
        {
            { "Id", Id },
            { propertyName, Text }
        }
    
        return jObject;
    }
    

    Then for Deserializing i would probably create a factory method something like this:

    public static Home CreateFromJObject(JObject obj)
    {
        Home h = new Home();
    
        foreach (var a in obj)
        {
            if (a.Key == "ID")
            {
                h.Id = a.Value.Value<int>();
            }
            else
            {
                h.propertyName = a.Key;
                h.Text = a.Value.Value<string>();
            }
        }
    
        return h;
    }
    

    Ofcause if you have multiple other values in there i would either change it to a switch or make sure that only the needed JObject is passed in there.