I am using RestSharp and would like to JSON serialize the request with the DTO's class name as root element. Here's an example DTO class:
public class NewToken {
public string user_name { get; set; }
public string password { get; set; }
public string audience { get; set; }
}
I would like the request generated to be:
{ "NewToken" : { "user_name": "asdf", "password": "asdfasdf", "audience": "test" }}
I realise I can use anonymous class such as this, but is there a way I can do this automatically using the class name as root element?
Here are some more code snippets for the API client:
public abstract class ApiBase
{
internal string _defaultServer = Properties.Settings.Default.DefaultServer;
internal int _defaultPort = Properties.Settings.Default.DefaultPort;
public T Execute<T>(RestRequest request) where T : new()
{
var client = new RestClient();
client.AddHandler("application/json", new CustomJsonSerialiser());
client.BaseUrl = new Uri($"https://{this._defaultServer}:{this._defaultPort}");
client.CookieContainer = new CookieContainer();
var response = client.Execute<T>(request);
return response.Data;
}
internal RestRequest CreateBasicRequest()
{
var request = new RestRequest();
request.RequestFormat = DataFormat.Json;
request.JsonSerializer = new CustomJsonSerialiser();
request.AddHeader("Accept", "application/json, application/binary");
request.AddHeader("Content-Type", "application/json");
return request;
}
internal RestRequest CreateAuthenticatedRequest(string tokenId)
{
var request = this.CreateBasicRequest();
request.AddHeader("Authorization", $"Bearer {tokenId}");
return request;
}
}
public class SessionManager : ApiBase
{
public SessionManager() { }
public SessionManager(string server, int port)
{
this._defaultServer = server;
this._defaultPort = port;
}
public Token GetToken()
{
var request = this.CreateBasicRequest();
request.Method = Method.POST;
request.Resource = "token";
request.AddBody(new { NewToken = new NewToken() { user_name = "dotnet", password = "dotnetdotnet", audience = "api" } });
var token = Execute<Token>(request);
return token;
}
public Token RenewToken(Token token)
{
var request = this.CreateAuthenticatedRequest(token.id);
request.Method = Method.POST;
request.Resource = "token-renew";
var new_token = Execute<Token>(request);
return new_token;
}
}
In SessionManager.GetToken()
I am creating an anonymous object to get it serialised correctly. I'm after an automated way, something integrated into the serialisation process, that will wrap the object in a root element with the same name as the DTO class.