C# MVC JsonConvert.SerializeObject-如何获取列和数据行数组
我正在使用MVC5和JsonConvert.SerializeObject序列化viewmodel,结果是为每个记录生成一个数组(例如,[{PropertyName:Value,…},{PropertyName:Value,…}]。我正在尝试填充一个光滑的网格以动态获取属性名称,我看到其他数组在一个数组中包含属性名称,然后在另一个数组中包含数据行。如何创建[{Column names},{DataRowValues}]因此,我可以从此数组中获取属性名称。我还将反序列化此数据。我使用此链接作为引用,但使用列表时遇到问题。谢谢C# MVC JsonConvert.SerializeObject-如何获取列和数据行数组,c#,asp.net-mvc,json,asp.net-mvc-5,C#,Asp.net Mvc,Json,Asp.net Mvc 5,我正在使用MVC5和JsonConvert.SerializeObject序列化viewmodel,结果是为每个记录生成一个数组(例如,[{PropertyName:Value,…},{PropertyName:Value,…}]。我正在尝试填充一个光滑的网格以动态获取属性名称,我看到其他数组在一个数组中包含属性名称,然后在另一个数组中包含数据行。如何创建[{Column names},{DataRowValues}]因此,我可以从此数组中获取属性名称。我还将反序列化此数据。我使用此链接作为引用
在服务器上,如果需要动态属性解析,可以使用反射来枚举视图模型的属性和值 由于您希望将JSON拆分为一个属性名称数组和一个属性值数组,因此我们需要一个类来保存该结果
class ObjectPropertyNamesAndValues
{
public List<string> Names { get; set; }
public List<object> Values { get; set; }
}
现在,您可以实现如下功能:
[HttpGet]
public JsonResult GeneratePlans()
{
//code here to create and populate view model
// get the object properties and values for transport as JSON
Debug.Assert(viewModel != null);
var objectPropertyNamesAndValues = GetObjectPropertyNamesAndValues(viewModel);
return Json(JsonConvert.SerializeObject(objectPropertyNamesAndValues, Formatting.Indented, new JsonSerializerSettings { }), JsonRequestBehavior.AllowGet);
}
viewmodel是什么样子的?谢谢,我会尝试一下,让你知道它是谁的
ObjectPropertyNamesAndValues GetObjectPropertyNamesAndValues(object viewModel)
{
if (viewModel == null)
return null;
var result = new JsonObjectPropertyValues();
result.Names = new List<string>();
result.Values = new List<object>();
var propertyInfo = viewModel.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach (var property in propertyInfo)
{
if (!propertyInfo.CanRead)
continue;
// you can add other checks here, too, such as whether or not
// the property has a certain custom attribute or not
result.Names.Add(propertyInfo.Name);
result.Values.Add(property.GetValue(viewModel));
}
return result;
}
[HttpGet]
public JsonResult GeneratePlans()
{
//code here to create and populate view model
// get the object properties and values for transport as JSON
Debug.Assert(viewModel != null);
var objectPropertyNamesAndValues = GetObjectPropertyNamesAndValues(viewModel);
return Json(JsonConvert.SerializeObject(objectPropertyNamesAndValues, Formatting.Indented, new JsonSerializerSettings { }), JsonRequestBehavior.AllowGet);
}