使用类名作为根元素序列化对象

时间:2016-08-19 02:39:12

标签: c# json restsharp

我正在使用RestSharp,并希望JSON使用DTO的类名作为根元素来序列化请求。这是DTO课程的一个例子:

public class NewToken {
    public string user_name { get; set; }
    public string password { get; set; }
    public string audience { get; set; }
}

我希望生成的请求为:

{ "NewToken" : { "user_name": "asdf", "password": "asdfasdf", "audience": "test" }}

我意识到我可以使用this之类的匿名类,但有没有办法可以使用类名作为根元素自动执行此操作?

以下是API客户端的更多代码段:

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;
        }
    }

SessionManager.GetToken()我正在创建一个匿名对象以使其正确序列化。我在自动化方式之后,集成到序列化过程中的东西,将对象包装在与DTO类同名的根元素中。

1 个答案:

答案 0 :(得分:0)

创建请求时,请使用request.RootElement = "NewToken";