Вопрос

I have a custom JSON object that I'd like to give a name to when it's serialized :

[JsonObject(Title = "AuthenticateResponse")]
public class AuthenticateResponse
{
    /// <summary>
    /// Gets or sets the status message to return to the patron.
    /// </summary>
    public string StatusMessage { get; set; }

    /// <summary>
    /// Gets or sets the Ils Message.
    /// </summary>
    public string IlsMessage { get; set; }

    /// <summary>
    /// Gets or sets the Ils code that was returned by the authentication attempt
    /// </summary>
    public string IlsCode { get; set; }
}

However, when this object is serialized, I'm only getting an output of the properties, without the object name :

AuthenticateResponse ar = new AuthenticateResponse();
ar.StatusMessage = "Test status Message";
ar.IlsMessage = "Test IlsMessage";
ar.IlsCode = "Code 614";

string json = JsonConvert.SerializeObject(ar);

The output from json is :

{
     "StatusMessage": "Test status Message",
     "IlsMessage": "Test IlsMessage",
     "IlsCode": "Code 614"
}

What I would like for it to be is the following :

{
     "AuthenticateResponse": {
         "StatusMessage": "Test status Message",
         "IlsMessage": "Test IlsMessage",
         "IlsCode": "Code 614"
      }
}

My Question :

What is the correct way of doing this?

Это было полезно?

Решение

Create a class like JsonObjectContainer

public class JsonObjectContainer
{
    public JsonObjectContainer() 
    { 
         AuthenticateResponse=new AuthenticateResponse();
    }
    public AuthenticateResponse AuthenticateResponse { get; set; }
}

Use it instead of AuthenticateResponse

JsonObjectContainer ar = new JsonObjectContainer();
ar.AuthenticateResponse.StatusMessage = "Test status Message";
ar.AuthenticateResponse.IlsMessage = "Test IlsMessage";
ar.AuthenticateResponse.IlsCode = "Code 614";

string json = JsonConvert.SerializeObject(ar);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top