【发布时间】:2019-12-05 07:18:20
【问题描述】:
以前(在 .Net Core 2.1 中)我使用以下方法成功处理 JSON 数据
[HttpPost]
[Route("sendJsonData")]
public JObject saveTemplate(JObject jsonString)
{
string templateName = (string)jsonString.SelectToken("templateName");
string filePathAndName = "D:\\" + "templates\\" + templateName + ".txt";
using (StreamWriter file = File.CreateText(@filePathAndName))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, jsonString);
}
return jsonString;
}
但是当我使用 .Net Core 3.1 创建相同的方法时。它无法显示 JObject 的一些错误。 我从下面的代码中得到那个 JSON
onSubmit() {
this.http.post("https://localhost:44350/ReportAPI/sendJsonData", this.surveyForm.value)
.subscribe(
data => console.log("success!", data),
error => console.error("couldn't post because", error)
);
}
以下是错误(邮递员的回应)
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|6e209814-4dd7396cc2dfa182.",
"errors": {
"$": [
"The JSON value could not be converted to System.Collections.Generic.IEnumerable`1[Newtonsoft.Json.Linq.JToken]. Path: $ | LineNumber: 0 | BytePositionInLine: 14."
]
}
}
JSON
{
"templateName":"BFS Survey",
"surveyQuestions":[
{
"questionTitle":"Name",
"questionType":"Text",
"questionGroup":{
}
},
{
"questionTitle":"Age",
"questionType":"Number",
"questionGroup":{
}
},
{
"questionTitle":"Gender",
"questionType":"Single choice",
"questionGroup":{
"options":[
{
"optionText":"Male"
},
{
"optionText":"Female"
},
{
"optionText":"Other"
}
],
"showRemarksBox":false
}
},
{
"questionTitle":"Skills",
"questionType":"Multi choice",
"questionGroup":{
"options":[
{
"optionText":"Java"
},
{
"optionText":"Angular"
},
{
"optionText":"Python"
},
{
"optionText":"R"
}
],
"showRemarksBox":false
}
}
]
}
代码使用 .Net Core 2.1 完美运行,但不适用于 3.1。请建议我如何解决此问题。
【问题讨论】:
-
你能发布那个错误
-
我有很多关于这个实现的问题......你能告诉我们错误吗?通常,使用专用类来反序列化请求正文中的 json,而不是普通的 JObject。另外,你为什么要捕获一个错误只是为了再次抛出它?你可以摆脱整个 try catch 块,它的行为完全相同
-
请查看更新后的问题以了解错误。 @GlennvanAcker
-
请查看更新后的问题以了解错误。 @Rajesh
-
@RahulSharma 成功了!!!非常感谢。真的很感激。 :)