elp*_*guy 5 c# json json.net asp.net-core-webapi asp.net-core-3.1
我正在 .net core 3.1 中编写一个简单的 API。要将我的数据表转换为 JSON 字符串,我使用 NewtonSoft 库和以下代码:
string JSONresult = JsonConvert.SerializeObject(dt, Formatting.Indented);
return Json (new { JSONresult });
我得到的输出是 JSON 字符串,但它有很多像 '\u0022' 这样的字符,我知道它是双引号。
{"jsoNresult":"[\r\n  {\r\n    \u0022ID\u0022: 2,\r\n    \u0022FunctionalityName\u0022: \u0022User Upload\u0022,\r\n    \u0022FunctionalityDescription\u0022: \u0022For Bulk Uploading User At Once\u0022,\r\n    \u0022TableName\u0022: \u0022tablename\u0022,\r\n    \u0022ValidationSP\u0022: \u0022user_Validate\u0022,\r\n    \u0022InsertSP\u0022: \u0022Insert_User\u0022\r\n  }\r\n]"}
我想要的是:
{"jsoNresult":"[{"ID": "2","FunctionalityName": "User Upload","FunctionalityDescription": "For Bulk Uploading User At Once","TableName": "tablename","ValidationSP": "user_Validate","InsertSP": "Insert_User"}]"}
我是 c# 新手,但之前曾在 Flask 甚至 Spring Boot 上工作过,他们返回清晰的 json 字符串。
那么我如何在 .net core 3.1 中实现我想要的。PS:我知道使用Formatting.Indented,我可以有或没有它的序列化字符串
第一个线索是你的 JSON 字符串
{"jsoNresult":"[\r\n  {\r\n    \u0022ID\u0022: 2,\r\n    \u0022FunctionalityName\u0022: \u0022User Upload\u0022,\r\n    \u0022FunctionalityDescription\u0022: \u0022For Bulk Uploading User At Once\u0022,\r\n    \u0022TableName\u0022: \u0022tablename\u0022,\r\n    \u0022ValidationSP\u0022: \u0022user_Validate\u0022,\r\n    \u0022InsertSP\u0022: \u0022Insert_User\u0022\r\n  }\r\n]"}
看起来它包含一个 JSON 字符串:[\r\n  {\r\n    \u0022ID\u0022看起来很像 JSON,记住它\u0022是引号"字符(值为 0x22 的 ascii 字符是")。
由此我们可以得出代码:
string JSONresult = JsonConvert.SerializeObject(dt, Formatting.Indented);
return Json (new { JSONresult });
实际上是对 JSON 进行了两次编码。Once 显然是JsonConvert.SerializeObject,但 other 可能是Json对象。
由此可以很清楚地看出,Json期望对象进行序列化,并且它将自行进行序列化。您不需要向其传递序列化字符串。
文档支持这一点,其中说:
创建一个 JsonResult 对象,将指定的数据对象序列化为 JSON。
所以尝试:
return Json(new { JSONresult = dt })
| 归档时间: | 
 | 
| 查看次数: | 6505 次 | 
| 最近记录: |