我有一个自定义的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"
}
}
我的问题:
这样做的正确方法是什么?
答案 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);