I use the fantastic Newtonsoft json.Net library (version 4.5.7.15008) for serialization and deserialization.
I would like to:
- Ignore the
.Databag property when serializing. - Configure JSON. First get the default JSON, change it and write the changed JSON to the result.
These are my classes:
public interface ISimpleDatabag { string Databag { get; set; } } [JsonConverter(typeof(JsonDataBagCreationConverter<Department>))] public class Department : ISimpleDatabag { [JsonIgnoreAttribute] public string Databag { get; set; } public string Name { get; set; } public Telephone[] Phones { get; set; } } [JsonConverter(typeof(JsonDataBagCreationConverter<Telephone>))] public class Telephone : ISimpleDatabag { [JsonIgnoreAttribute] public string Databag { get; set; } public string Name { get; set; } public string AreaCode { get; set; } public string Number { get; set; } } public class JsonDataBagCreationConverter<T> : JsonConverter where T : ISimpleDatabag, new() {
And the call:
public Form1() { InitializeComponent(); string jsonInput = "{\"Name\": \"Seek4\" , \"CustomDepartmentData\": \"This is custom department data\", \"Phones\":[ {\"Name\": \"A\", \"AreaCode\":444, \"Number\":11111111} ,{\"Name\": \"B\", \"AreaCode\":555, \"Number\":987987987}, {\"Name\": \"C\", \"AreaCode\":222, \"Number\":123123123, \"CustomPhoneData\": \"This is custom phone data\"} ] }"; Department objDepartment = JsonConvert.DeserializeObject<Department>(jsonInput); // Yes, it works well objDepartment.Name = "Seek4Cars"; string json = ToSeek4Json(objDepartment); // This is my problem: Ignore Databag property and control the output json for each property } public static string ToSeek4Json(object objectToConvertToJson) { JsonSerializerSettings serializerSettings = new JsonSerializerSettings(); IgnoreDataBagContractResolver contractResolver = new IgnoreDataBagContractResolver(); serializerSettings.ContractResolver = contractResolver; return JsonConvert.SerializeObject(objectToConvertToJson, Formatting.None, serializerSettings); }
source share