JSON.net Linq和NullValueHandling

时间:2014-03-20 00:14:34

标签: linq asp.net-mvc-4 json.net

开发一个新的MVC4应用程序,我在JSON.net网站上关注了这个example,用一个新的JSON JObject来填充我的viewmodel:

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代码。

1 个答案:

答案 0 :(得分:0)

不使用JObjects作为LINQ转换的一部分,而是使用匿名对象。 (这也会使您的代码更具可读性!)之后,您可以使用JObject实例JsonSerializer将结果对象加载到NullValueHandlingIgnore设置为{{ 1}}。这将摆脱空值。这是一个演示:

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);