我有objets列表,并在下面的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...",…}
]
答案 0 :(得分:0)
您正在使用new { }
将对象包装到包装对象中。
抛弃new { }
包装器,然后选择ConversionMeta
属性本身。
public JsonResult ConversionInfo(string srcFormat)
{
return Json(MetadataDbService.FindBySourceFormat(srcFormat).Select(m => m.ConversionMeta), JsonRequestBehavior.AllowGet);
}
答案 1 :(得分:0)
我建议创建一个包含所有属性的类,并使用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..."}
]