【发布时间】:2020-01-21 00:48:44
【问题描述】:
我正在尝试输出 JSON 文件。我正在使用 netcoreapp3.1 和 Newtonsoft.Json NuGet。这是我输入所有信息的代码:
private BlockWrapper GetBlock()
{
var blockWrapper = new BlockWrapper
{
blocks = new List<IntBlock>
{
new SectionBlockBlock
{
text = new TextBlock
{
type = "mrkdwn",
text = "Hello! I am Multiuse Kat. How can I help you ?"
}
},
new ActionsBlockBlock
{
elements = new ElementBlock[]
{
new ElementBlock
{
type = "button",
text = new TextBlock
{
type = "plain_text",
text = "Help"
},
style = "primary",
value = "click_me_123"
}
}
},
}
};
return blockWrapper;
}
我的模型看起来像这样。请注意,我正在使用 IntBlock 的接口:
public class BlockWrapper
{
public List<IntBlock> blocks { get; set; }
}
public class SectionBlockBlock : IntBlock
{
public string type { get; } = "section";
public string blockId { get; set; }
public TextBlock text { get; set; }
}
public class ActionsBlockBlock : IntBlock
{
public string type { get; } = "actions";
public string blockId { get; set; }
public ElementBlock[] elements { get; set; }
}
public class TextBlock
{
public string type { get; set; }
public string text { get; set; }
public bool? emoji { get; set; }
}
public class ElementBlock
{
public string type { get; set; }
public string action_id { get; set; }
public TextBlock text { get; set; }
public string value { get; set; }
public string style { get; set; }
}
public interface IntBlock { }
当我返回 new JsonResult(GetBlock());我输出这个:
我假设这与 IntBlock 的接口有关。有人可以告诉我如何解决这个问题吗?谢谢!
【问题讨论】:
-
你使用的是什么 MVC 框架和版本?
-
是asp.net-core-3.0 还是asp.net-core-3.1?您几乎提供了minimal reproducible example,有关该框架的详细信息将使您的问题得到解答。我们基本上需要能够弄清楚您使用的是什么 JSON 序列化器。
-
谢谢。我已经编辑了这些细节:我正在使用 netcoreapp3.1 和 Newtonsoft.Json NuGet
-
与 Newtonsoft.Json NuGet 一起 - 好的,但您是否还添加了
Microsoft.AspNetCore.Mvc.NewtonsoftJsonnuget 并在ConfigureServices()中调用.AddNewtonsoftJson();?如果没有,您将改用System.Text.Json,我相信它将根据它们声明的类型而不是它们的实际类型来序列化属性值。请参阅:Where did IMvcBuilder AddJsonOptions go in .Net Core 3.0?。 -
成功了!谢谢。
标签: c# json model-view-controller slack