Mrinal Kamboj
Mrinal Kamboj

Reputation: 11478

Removing empty elements from the serialized Json

Following is my Json serialization code with CustomResolver, check the difference between Actual and Expected results at the end. I am not able to remove the empty elements from the final result. There's an option available here, but in my real application, which use ASP.Net Web API, I don't have the liberty to call JsonConvert.SerializeObject, it is called automatically, probably need a way to do it in the Custom Contract Resolver, any help / pointer would be great

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

Actual Result:

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

Expected Result:

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

Upvotes: 0

Views: 1486

Answers (1)

mjwills
mjwills

Reputation: 23975

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

should possibly be replaced with:

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

The Where clause will ensure that you serialise only the 'non-null' data.

Upvotes: 1

Related Questions