gpt4 book ai didi

c# - 从 2 个不同的字典构建 Json 字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 13:48:37 24 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于c# - 从 2 个不同的字典构建 Json 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14405883/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com