2014-04-09 12 views
0

被應用我有一個自定義的JSON對象,我想給一個名字時,它的序列化:JSONObject的標題不是系列化

[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

創建像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); 
+0

雖然這併產生正確的JSON輸出,我更感興趣的是使用特定JSON.Net屬性來完成這不需要將我的對象包裝在容器類中。如果沒有包裝,沒有辦法實現這一點嗎? – X3074861X

+0

我不知道它是否會工作在兩種方式序列化/反序列化 – csharpwinphonexaml

+0

我沒有發現什麼更容易/清潔 – csharpwinphonexaml