2

我正在使用 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."
        }
}

我基本上是在努力实现这一目标。

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)。

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

4

1 回答 1

1

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

于 2013-01-18T20:05:06.480 回答