JSON为空,在MVC中使用JsonResult类型

问题描述 投票:0回答:1

我正在尝试输出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 { }

当我返回新的JsonResult(GetBlock());我输出这个:

enter image description here

我假设这与IntBlock的界面有关。有人可以告诉我如何解决这个问题吗?谢谢!

c# json model-view-controller slack
1个回答
1
投票

尝试使用此

return JsonConvert.SerializeObject(GetBlock());

我总是使用上述方法,并且一切正常。

而且,您的interface属性是null

public interface IntBlock { }

因此,您的集合类型为空接口,并且序列化程序将找不到任何属性来对其进行序列化。

我认为下面的代码应该可以工作

public class ActionsBlockBlock : IntBlock
{
    IntBlock.type { get; } = "actions";
    IntBlock.blockId { get; set; }
    IntBlock.ElementBlock[] elements { get; set; }
}
public interface IntBlock 
{ 
    public string type { get; set; }
    public string blockId { get; set; }
    public ElementBlock[] elements { get; set; }
}

对您所有的类都执行以上架构,然后重试。我认为它有效。

© www.soinside.com 2019 - 2024. All rights reserved.