Home > Back-end >  How to serialize only property names when object is empty?
How to serialize only property names when object is empty?

Time:12-09

I have working code for serialization into json:

using Newtonsoft.Json;

 public async Task<string> Handle(ConvertToJsonQuery request, CancellationToken cancellationToken)
    {
       return Serialize(PrepareObjectForSerialization(request), LanguageEnum.HR);
    }


 private object PrepareObjectForSerialization(ConvertToJsonQuery request)
    {
        Type listType = typeof(List<>).MakeGenericType(Type.GetType(request.TypeOfList));
        return JsonConvert.DeserializeObject(request.Data, listType);
    }


private string Serialize(object obj, LanguageEnum lang)
        {
            var settings = new JsonSerializerSettings
            {
                ContractResolver = new MultiLangResolver(lang),
                Formatting = Newtonsoft.Json.Formatting.Indented,
                
            };
            return JsonConvert.SerializeObject(obj, settings);  
        }

And this code works if request.Data is not empty. Example:

  [
        {
            "Institution": "19.10.",
            "FemaleTotal": 1,
          
        },
        {
            "Institution": "my institution",
            "FemaleTotal": 2,
        }
]

But, if it is empty I get [] as a response. How to change this, so when request.Data is empty I get only property names. For example above, if request.Data is empty I should get

  [
        {
            "Institution": null,
            "FemaleTotal": null             
        }
]

CodePudding user response:

To serialize an instance you will need the class like this

public class Data
{
    public string Institution { get; set; }
    public int? FemaleTotal { get; set; }
}

string is nullable by default,if you make FemaleTotal nullable too, you will get this json by default, you don't need any serializer options

[
  {
    "Institution": null,
    "FemaleTotal": null
  }
]
  • Related