开发一个新的MVC4应用程序,我在JSON.net网站上遵循这个例子,用一个新的JSON JObject填充我的视图模型:
FinalViewModel finalVM= new FinalViewModel();
IList<ResultModel> results = GetResultList();
FinalVM.QueryResults = results;
JObject myJSON = new JObject(
new JProperty("grid",
new JArray(
from g in results
group g by g.ResultYear into y
orderby y.Key
select new JObject {
new JProperty("Year", y.Key),
new JProperty("min_1", y.Min(g=> g.Result_val1)),
new JProperty("min_2", y.Min(g=> g.Result_val2)),
new JProperty("items",
new JArray(
from g in results
where g.ResultYear==y.Key
orderby g.id
select new JObject(
new JProperty("l", g.Result_val1),
new JProperty("j",g.Result_val2),
new JProperty("id", g.id)
)
)
)}
)));
FinalVM.DataJson = myJSON;
return PartialView("_JSONView", FinalVM);
一切正常,我得到这个类型的json发送到我的视图:
{
"grid": [
{
"Year": 1998,
"min_val1": "12",
"min_val2": null,
"items": [
{
"l": 12,
"j": null,
"id": 60
},
{
"l": 25,
"j": null,
"id": 61
}
]
}
]
}
我想摆脱空值时,他们存在。我读了很多关于NullValueHandling
选项,但不知道如何使用它到我的Json。Net linq代码。
不要在LINQ转换中创建JObjects
,而是使用匿名对象。(这也会使你的代码可读性大大提高!)之后,您可以使用NullValueHandling
设置为Ignore
的JsonSerializer
实例将结果对象加载到JObject
中。这样就去掉了空。下面是一个演示:
class Program
{
static void Main(string[] args)
{
IList<ResultModel> results = new List<ResultModel>
{
new ResultModel
{
id = 60,
ResultYear = 1998,
Result_val1 = 12,
Result_val2 = null
},
new ResultModel
{
id = 61,
ResultYear = 1998,
Result_val1 = 25,
Result_val2 = null
}
};
var groupedResult = new
{
grid = from g in results
group g by g.ResultYear into y
orderby y.Key
select new
{
Year = y.Key,
min_1 = y.Min(g => g.Result_val1),
min_2 = y.Min(g => g.Result_val2),
items = from g in results
where g.ResultYear == y.Key
orderby g.id
select new
{
l = g.Result_val1,
j = g.Result_val2,
id = g.id
}
}
};
JsonSerializer serializer = new JsonSerializer();
serializer.NullValueHandling = NullValueHandling.Ignore;
JObject myJSON = JObject.FromObject(groupedResult, serializer);
Console.WriteLine(myJSON.ToString(Formatting.Indented));
}
class ResultModel
{
public int id { get; set; }
public int ResultYear { get; set; }
public int? Result_val1 { get; set; }
public int? Result_val2 { get; set; }
}
}
输出:{
"grid": [
{
"Year": 1998,
"min_1": 12,
"items": [
{
"l": 12,
"id": 60
},
{
"l": 25,
"id": 61
}
]
}
]
}
另一个注意事项:如果您不打算操作JSON,您实际上可以完全跳过JObject
,并将分组结果直接序列化为字符串:
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.Formatting = Formatting.Indented;
string myJSON = JsonConvert.SerializeObject(groupedResult, settings);