如何序列化只有属性名称时,对象是空的?



我有工作代码序列化成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);  
}

如果request.Data不为空,则此代码有效。例子:

[
{
"Institution": "19.10.",
"FemaleTotal": 1,

},
{
"Institution": "my institution",
"FemaleTotal": 2,
}
]

但是,如果它是空的,我得到[]作为响应。如何改变这一点,所以当request.Data是空的,我只得到属性名称。例如,如果request.Data为空,我应该得到

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

要序列化一个实例,您需要这样的类

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

string默认为空,如果你也让FemaleTotal为空,你将默认得到这个json,你不需要任何序列化器选项

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

相关内容

  • 没有找到相关文章

最新更新