有没有一种平衡的方法可以使用单个类在c#中序列化两级对象



我需要以这种方式从控制器输出json结果:{ x: { myProp1: false, myProp2:"xx" } }我希望传递给Json(obj)的对象是没有嵌套类的类的实例。有没有任何方法可以使类MyResult产生我想要的结果,而不必创建包装器独立类或对象?

我想要所有:

  • 能够生成调用return Json(new MyResult());的正确响应
  • MyResult类保留为单个文件中的单个类
  • 没有过度工程化

正在寻找最好的方法。

当前代码:

[Serializable]
class MyResult{
[JsonPropertyName("myProp1")]
public bool Property1 {get; init;} = false; 
[JsonPropertyName("myProp2")]
public string Property2 {get; init;} = "xx";
public MyResult(bool p1 = true, string p2 = "xx") {
Property1 = p1;
Property2 = p2;
}
}
...

public class MyController : Controller
[AllowAnonymous]
[HttpGet("GetMyResult")]
[Produces("application/json")]
public IActionResult GetMyResult() {
return Json(new {x = new MyResult()}); // I want this to be return Json(new MyResult());
}
[AllowAnonymous]
[HttpGet]
[Produces("application/json")]
public IActionResult GetMyResult()
{
return Json(new MyResult()); 
}
public override JsonResult Json(object data) 
=> new JsonResult( new { x = data });
  • ✅能够生成正确的响应调用返回Json(new MyResult(((
  • ✅将MyResult类保留为单个文件中的单个类
  • ✅没有过度工程化

最新更新