有没有办法更新JSON密钥名称或更改json的现有Keyname?
class NewBands
{
private List<NSongs> _NBandName;
public string NewBandName { get; set; }
public List<NSongs> NBandName
{
get { return _NBandName; }
set { _NBandName = value; }
}
}
class NSongs
{
public string NSongTitle { get; set; }
}
[HttpPost]
public JsonResult Bands()
{
dbBandsEntities dbband = new dbBandsEntities();
var returnjson = dbband.Bands.AsEnumerable().Select(x => new NewBands()
{
NewBandName = x.BandName.ToString(),
NBandName = dbband.BandSongs.AsEnumerable().Where(y => y.BandId == x.Id).Select(z => new NSongs() {
NSongTitle = z.SongTitle
}).ToList()
});
return Json(returnjson, JsonRequestBehavior.AllowGet);
}
输出:
[{ “NewBandName”:“Amber Pacific”, “NBandName”:[ {“NSongTitle”:“倒回我的手臂”}, {“NSongTitle”:“如果我跌倒”}, {“NSongTitle”:“当我找到你的时候”} ]},{ “NewBandName”:“五月天游行”, “NBandName”:[ {“NSongTitle”:“野兽可怜”}, {“NSongTitle”:“我无法看到大图片的问题”} ]},{ “NewBandName”:“Fm Static”, “NBandName”:[ {“NSongTitle”:“亲爱的上帝”}, {“NSongTitle”:“她的父歌”}, {“NSongTitle”:“末班车之家”}, {“NSongTitle”:“今晚”}, {“NSongTitle”:“黑色纹身”} ]}
我想将NBandName更新为BandName本身。
输出应该是: { “NewBandName”:“Amber Pacific”, “琥珀太平洋”:[ {“NSongTitle”:“倒回我的手臂”}, {“NSongTitle”:“如果我跌倒”}, {“NSongTitle”:“当我找到你的时候”} ] } ......
答案 0 :(得分:1)
您可以创建字符串键和对象值的字典列表,而不是创建NewBands
个对象的列表。这允许动态设置任意键名称:
var returnjson = dbband.Bands.AsEnumerable().Select(x => new Dictionary<string, object>
{
{ "NewBandName", x.BandName.ToString() },
{
x.BandName.ToString(),
dbband.BandSongs
.AsEnumerable()
.Where(y => y.BandId == x.Id)
.Select(z => new NSongs() {
NSongTitle = z.SongTitle
})
.ToList()
}
});