JsonObject标题未在序列化中应用

时间:2014-04-09 21:01:22

标签: c# json json.net

我有一个自定义的JSON对象,我希望在它被序列化时给出一个名称:

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

但是,当序列化此对象时,我只获取属性的输出,而没有对象名称:

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

string json = JsonConvert.SerializeObject(ar);

json的输出是:

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

喜欢它的内容如下:

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

我的问题:

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

创建一个类似JsonObjectContainer

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

使用它代替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);