2013-01-18 63 views
2

我正在使用json.net(newtonsoft),我想構建一個json請求,但我有2個不同的字典,不知道如何加入它們。從2個不同的字典構建Json字符串?

Dictionary<string, HttpStatusCode> code = new Dictionary<string, HttpStatusCode>(); 
    code.Add("Message", statusCode); 

Dictionary<string, IErrorInfo> modelState = new Dictionary<string, IErrorInfo>(); 
// some code to add to this modelState 

編輯

的IErrorInfo只是有一些屬性

public interface IErrorInfo 
    { 
     SeverityType SeverityType { get; set; } 
     ValidationType ValidationType { get; set; } 
     string Msg { get; set; } 
    } 

我試圖去的結果是這樣的

{ 
    "Message": 400, // want this to be text but not sure how to do that yet (see below) 
    "DbError":{ 
     "SeverityType":3, 
     "ValidationType":2, 
     "Msg":"A database error has occurred please try again." 
     } 
} 

我基本上是試圖實現this

HttpError and Model Validation 

For model validation, you can pass the model state to CreateErrorResponse, to include the validation errors in the response: 

public HttpResponseMessage PostProduct(Product item) 
{ 
    if (!ModelState.IsValid) 
    { 
     return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); 
    } 

    // Implementation not shown... 
} 

This example might return the following response: 

HTTP/1.1 400 Bad Request 
Content-Type: application/json; charset=utf-8 
Content-Length: 320 

{ 
    "Message": "The request is invalid.", 
    "ModelState": { 
    "item": [ 
     "Required property 'Name' not found in JSON. Path '', line 1, position 14." 
    ], 
    "item.Name": [ 
     "The Name field is required." 
    ], 
    "item.Price": [ 
     "The field Price must be between 0 and 999." 
    ] 
    } 
} 

我不使用這種內置方法的原因是因爲我有一個單獨的內置類庫,其中包含我所有的業務邏輯。我想保持它,以便它不依賴於網絡的東西或mvc的東西(如modelState)。

這就是爲什麼我創建了我自己的模型狀態與一些額外的東西在裏面。

+3

你想要'最終'結果看起來像什麼?樣本json .... – Alex

+0

'json請求'的格式是什麼?什麼是「IErrorInfo」? – I4V

回答

1

您應該只能使用一個詞典並將兩個詞典中的項目添加到該詞典中。 Json.NET應該像你期待的那樣序列化它。

相關問題