T.J*_*der 5 c# json azure-functions
我使用 Azure 函数返回一个对象OkObjectResult,但该对象的 JSON 仍然包含我标记的属性JsonIgnore。为什么会这样,我该如何解决它?
细节:
我有这门课:
using System.Text.Json.Serialization;
// ...
public class Example
{
public string A { get; set; }
public string B { get; set; }
[JsonIgnore]
public string C { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
从 Azure 函数返回时,如果我这样做:
var result = new Example() { A = "Ayy", B = "Bee", C = "See" };
return new OkObjectResult(result);
Run Code Online (Sandbox Code Playgroud)
...返回的 JSON 是(我添加了格式):
{
a: "Ayy",
b: "Bee",
c: "See"
}
Run Code Online (Sandbox Code Playgroud)
注意,JsonIgnore属性没有生效,JSON 有一个c属性。
但如果我明确序列化:
var result = new Example() { A = "Ayy", B = "Bee", C = "See" };
return new OkObjectResult(
JsonSerializer.Serialize(
result,
new JsonSerializerOptions() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase}
)
);
Run Code Online (Sandbox Code Playgroud)
...c根据需要省略:
{
a: "Ayy",
b: "Bee"
}
Run Code Online (Sandbox Code Playgroud)
当我直接提供对象时,为什么属性没有被遗漏OkObjectResult,如何修复它?
问题是类代码使用了错误的JsonIgnore属性,因为:
Run Code Online (Sandbox Code Playgroud)using System.Text.Json.Serialization;
截至撰写本文时,Azure 函数(仍然)Newtonsoft.Json默认使用1 ,因此该属性被标记为错误的属性,并且序列化程序不知道是否将其遗漏。
要修复它,请导入Newtonsoft.Json:
using Newtonsoft.Json; // <====================
// ...
public class Example
{
public string A { get; set; }
public string B { get; set; }
[JsonIgnore]
public string C { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
1如果您使用 Visual Studio 的 Add...> Azure Function,它创建的模板包含 的导入Newtonsoft.Json,这是我意识到这一点的唯一原因。另请参阅此相关问题(感谢Eldar!)。
| 归档时间: |
|
| 查看次数: |
271 次 |
| 最近记录: |