从2个不同的词典构建Json字符串?

时间:2013-01-18 19:08:36

标签: c# .net asp.net-web-api json.net

我正在使用json.net(newtonsoft),我想构建一个json请求,但我有2个不同的词典,不知道如何加入它们。

   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."
    ]
  }
}

我没有使用这种内置方法的原因是因为我有一个单独的内置类库,其中包含我的所有业务逻辑。我想保留它,以便它不依赖于web东西或mvc东西(比如modelState)。

这就是我创建自己的模型状态的原因,其中包含一些额外的东西。

1 个答案:

答案 0 :(得分:1)

您应该只能使用一个词典,并将两个词典中的项目添加到此词典中。 Json.NET应该像你期望的那样对它进行序列化。