从序列化的Json中删除空元素

时间:2017-08-22 13:24:26

标签: c# json asp.net-web-api json.net

以下是我的Json serialization代码CustomResolver,请检查最后实际和预期结果之间的差异。我无法从最终结果中删除空元素。有一个可用的选项here,但在我使用ASP.Net Web API的真实应用程序中,我没有权限调用JsonConvert.SerializeObject,它会被自动调用,可能需要一种方法在Custom Contract Resolver中执行,任何帮助/指针都会很棒

void Main()
{
    var cbList = new List<CustomerBusiness>();

    cbList.Add(new CustomerBusiness { Id = null, Name = null, PhoneNumber = null });
    cbList.Add(new CustomerBusiness { Id = 1, Name = null, PhoneNumber = null });
    cbList.Add(new CustomerBusiness { Id = null, Name = "Mrinal", PhoneNumber = null });
    cbList.Add(new CustomerBusiness { Id = null, Name = null, PhoneNumber = "9886623261" });
    cbList.Add(new CustomerBusiness { Id = null, Name = null, PhoneNumber = null });
    cbList.Add(new CustomerBusiness { Id = null, Name = null, PhoneNumber = null });

    var serializedData = JsonConvert.SerializeObject(cbList, Newtonsoft.Json.Formatting.Indented,new JsonSerializerSettings { ContractResolver = new CustomResolver() });

    serializedData.Dump();
}

public class CustomResolver : DefaultContractResolver
{
    protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
    {
        IList<JsonProperty> retval = base.CreateProperties(type, memberSerialization);

        retval = retval.Select(p =>
        {
            p.PropertyName = char.ToLower(p.PropertyName[0]) + string.Join("", p.PropertyName.Skip(1));
            p.NullValueHandling = NullValueHandling.Ignore;
            return p;
        }).ToList();

        return retval;
    }
}

public class CustomerBusiness
{
    public int? Id { get; set; }

    public string Name { get; set; }

    public string PhoneNumber { get; set; }
}

实际结果:

[
  {},
  {
    "id": 1
  },
  {
    "name": "Mrinal"
  },
  {
    "phoneNumber": "9886623261"
  },
  {},
  {}
]

预期结果:

[
  {
    "id": 1
  },
  {
    "name": "Mrinal"
  },
  {
    "phoneNumber": "9886623261"
  }
]

1 个答案:

答案 0 :(得分:1)

var serializedData = JsonConvert.SerializeObject(
    cbList,
    Newtonsoft.Json.Formatting.Indented,new JsonSerializerSettings { ContractResolver = new CustomResolver() });

应该替换为:

var serializedData = JsonConvert.SerializeObject(
    cbList.Where(z => z.Id != null || z.Name != null || z.PhoneNumber != null),
    Newtonsoft.Json.Formatting.Indented,new JsonSerializerSettings { ContractResolver = new CustomResolver() });

Where子句将确保您仅序列化非空的&#39;数据