我应该输出JSON中的设置列表,我从数据库中获取并存储在Tuple<string, string>
中。
我能够打印它,但它不会显示它应该:
[{
"Item1": "setting1Name",
"Item2": "setting1Value"
}, {
"Item1": "testt",
"Item2": "testt"
}, {...
}]
输出应为:
[
{"setting1Name":"setting1Value"},
{"setting2Name":"setting2Value"},{...}
]
如何将元组序列化为JSON?
[GET("Settings")]
public async Task<ActionResult> Settings(string userKey)
{
if ((await UserManager.FindByIdAsync(userKey)) == null)
return new HttpUnauthorizedResult();
List<Tuple<string, string>> settings = new List<Tuple<string, string>>();
var userSettings = settingRepository.Get(new Guid(userKey));
for (int i = 0; i < userSettings.Count; i++)
{
var tuple = Tuple.Create<string, string>(
userSettings[i].Name.ToString(),
userSettings[i].Value.ToString()
);
settings.Add(tuple);
}
return Json(settings,JsonRequestBehavior.AllowGet);
}
public List<Setting> Get(Guid userId)
{
return _context.Settings.Where(s => s.UserId == userId).ToList();
}
答案 0 :(得分:0)
你可以玩这样的东西
替换此行
return Json(settings,JsonRequestBehavior.AllowGet);
使用
var dict = new Dictionary<string, string>();
settings.ForEach(a => dict.Add(a.Item1, a.Item2));
return Json(new List<Dictionary<string, string>>{dict},
JsonRequestBehavior.AllowGet);