Kamen
Kamen

Reputation: 3595

JSON.NET: Define C# field that can hold two different kind of objects

I have the following objects that I serialize with JSON.NET (not this in particular, but with similar structure).

  1. A basic class for request

    public class Request
    {
        public string version = "1.0";
        public RequestParams params;
    
        public Request(RequestParams params)
        {
            this.params = params;
        }
    }
    
  2. A basic payload class

    public abstract class RequestParams
    { }
    
  3. Payload classes

    public SampleRequest : RequestParams
    {
        public string someInfo = "param info";
    }
    
  4. Usage

    new Request(new SampleRequest());
    

This is all fine when I know the structure of the requests. However, sometimes I need to define dynamic object as "params" parameter. That is, I need to have "params" object be treated as a Dictionary (but without the []), so that I receive JSON in the format:

    {
        "version":"1.0",
        "params":{
            "dynamic":"x",
            ...any number of dynamically added fields
            "dynamic2":"y"
        }
    }

How can I do it?

Upvotes: 1

Views: 156

Answers (2)

Saeed Neamati
Saeed Neamati

Reputation: 35842

You can use dynamic and ExpandoObject:

dynamic parameters = new ExpandoObject();
parameters.Name = "Name";
parameters.Age = 30;
// Adding as much property as you like dynamically

this after serialization becomes:

{
    'Name': 'Name',
    'Age': 32,
    /* any other dynamic property */
}

Upvotes: 1

Gusdor
Gusdor

Reputation: 14334

Create a base Request class that pulls in its information from a params dictionary. This is your dynamic request object.

Create classes that inherit from Request that operate upon the dictionary, instead of members. These are you 'known' requests.

params is a keyword in .Net. Consider using another varaible name.

Upvotes: 2

Related Questions