将对象列表序列化为没有父对象名称的 JSON

Posted

技术标签:

【中文标题】将对象列表序列化为没有父对象名称的 JSON【英文标题】:Serialize objects list to JSon without Parent object name 【发布时间】:2019-03-01 06:52:19 【问题描述】:

我有对象列表并在我的 MVC 应用程序中使用下面的代码输出它们。

 public JsonResult ConversionInfo(string srcFormat)
        
            return Json(MetadataDbService.FindBySourceFormat(srcFormat).Select(m => new
            
                m.ConversionMeta
            ), JsonRequestBehavior.AllowGet);
        

代码产生这样的结果。每行/项目都以父对象名称 ConversionMeta 开头。

[
"ConversionMeta":"Id": "delete", "Name": "delete page from PDF", "Description": "You can delete any page from PDF blah blah...",…,
"ConversionMeta":"Id": "delete", "Name": "delete page from PDF", "Description": "You can delete any page from PDF blah blah...",…
]

我想要这样的结果,有什么想法可以修改代码吗?

[
"Id": "delete", "Name": "delete page from PDF", "Description": "You can delete any page from PDF blah blah...",…,
"Id": "delete", "Name": "delete page from PDF", "Description": "You can delete any page from PDF blah blah...",…
]

【问题讨论】:

【参考方案1】:

通过使用new 选择对象,您将对象包装在包装对象中。

放弃new 包装器,并选择ConversionMeta 属性本身。

public JsonResult ConversionInfo(string srcFormat)

    return Json(MetadataDbService.FindBySourceFormat(srcFormat).Select(m => m.ConversionMeta), JsonRequestBehavior.AllowGet);

【讨论】:

【参考方案2】:

我建议创建一个包含所有属性的类,并使用 JSON.NET 将该类序列化为 json

您可以通过 Nuget 安装 JSON.NET

PM> Install-Package Newtonsoft.Json

创建一个类的数组并用你的所有条目填充它

然后就可以使用JsonConvert.SerialzeObject方法来创建Json了

这是我的代码:

static void Main(string[] args)

    ConversionMeta[] conversionMetaArray = new ConversionMeta[3];
    conversionMetaArray[0] = new ConversionMeta()
    
        Id = "deleted",
        Name = "delete page from PDF",
        Description = "You can delete any page from PDF blah blah..."
    ;
    conversionMetaArray[1] = new ConversionMeta()
    
        Id = "deleted",
        Name = "delete page from PDF",
        Description = "You can delete any page from PDF blah blah..."
    ;
    conversionMetaArray[2] = new ConversionMeta()
    
        Id = "deleted",
        Name = "delete page from PDF",
        Description = "You can delete any page from PDF blah blah..."
    ;

    string json = JsonConvert.SerializeObject(conversionMetaArray);

这是课程:

class ConversionMeta

    public string Id  get; set; 
    public string Name  get; set; 
    public string Description  get; set; 

这是输出:

[
"Id":"deleted","Name":"delete page from PDF","Description":"You can delete any page from PDF blah blah...",
"Id":"deleted","Name":"delete page from PDF","Description":"You can delete any page from PDF blah blah...",
"Id":"deleted","Name":"delete page from PDF","Description":"You can delete any page from PDF blah blah..."
]

【讨论】:

以上是关于将对象列表序列化为没有父对象名称的 JSON的主要内容,如果未能解决你的问题,请参考以下文章

JSON:将 DataRow 序列化为父对象

将单个 KeyValuePair<> 序列化为 JSON 作为父对象的一部分

C# JSON 将文件反序列化为对象列表失败,并将字符串转换为集合错误

使用spring boot将JSON反序列化为带有通用对象列表的POJO

将特定 JSON 字段反序列化为 Unity 中的对象列表

如何将 django/python 中的模型对象列表序列化为 JSON