Newtonsoft JSON dynamic property name - c#

Is there a way to change name of Data property during serialization, so I can reuse this class in my WEB Api.
For an example, if i am returning paged list of users, Data property should be serialized as "users", if i'm returning list of items, should be called "items", etc.
Is something like this possible:
public class PagedData
{
[JsonProperty(PropertyName = "Set from constructor")]??
public IEnumerable<T> Data { get; private set; }
public int Count { get; private set; }
public int CurrentPage { get; private set; }
public int Offset { get; private set; }
public int RowsPerPage { get; private set; }
public int? PreviousPage { get; private set; }
public int? NextPage { get; private set; }
}
EDIT:
I would like to have a control over this functionality, such as passing name to be used if possible. If my class is called UserDTO, I still want serialized property to be called Users, not UserDTOs.
Example
var usersPagedData = new PagedData("Users", params...);

You can do this with a custom ContractResolver. The resolver can look for a custom attribute which will signal that you want the name of the JSON property to be based on the class of the items in the enumerable. If the item class has another attribute on it specifying its plural name, that name will then be used for the enumerable property, otherwise the item class name itself will be pluralized and used as the enumerable property name. Below is the code you would need.
First let's define some custom attributes:
public class JsonPropertyNameBasedOnItemClassAttribute : Attribute
{
}
public class JsonPluralNameAttribute : Attribute
{
public string PluralName { get; set; }
public JsonPluralNameAttribute(string pluralName)
{
PluralName = pluralName;
}
}
And then the resolver:
public class CustomResolver : DefaultContractResolver
{
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty prop = base.CreateProperty(member, memberSerialization);
if (prop.PropertyType.IsGenericType && member.GetCustomAttribute<JsonPropertyNameBasedOnItemClassAttribute>() != null)
{
Type itemType = prop.PropertyType.GetGenericArguments().First();
JsonPluralNameAttribute att = itemType.GetCustomAttribute<JsonPluralNameAttribute>();
prop.PropertyName = att != null ? att.PluralName : Pluralize(itemType.Name);
}
return prop;
}
protected string Pluralize(string name)
{
if (name.EndsWith("y") && !name.EndsWith("ay") && !name.EndsWith("ey") && !name.EndsWith("oy") && !name.EndsWith("uy"))
return name.Substring(0, name.Length - 1) + "ies";
if (name.EndsWith("s"))
return name + "es";
return name + "s";
}
}
Now you can decorate the variably-named property in your PagedData<T> class with the [JsonPropertyNameBasedOnItemClass] attribute:
public class PagedData<T>
{
[JsonPropertyNameBasedOnItemClass]
public IEnumerable<T> Data { get; private set; }
...
}
And decorate your DTO classes with the [JsonPluralName] attribute:
[JsonPluralName("Users")]
public class UserDTO
{
...
}
[JsonPluralName("Items")]
public class ItemDTO
{
...
}
Finally, to serialize, create an instance of JsonSerializerSettings, set the ContractResolver property, and pass the settings to JsonConvert.SerializeObject like so:
JsonSerializerSettings settings = new JsonSerializerSettings
{
ContractResolver = new CustomResolver()
};
string json = JsonConvert.SerializeObject(pagedData, settings);
Fiddle: https://dotnetfiddle.net/GqKBnx
If you're using Web API (looks like you are), then you can install the custom resolver into the pipeline via the Register method of the WebApiConfig class (in the App_Start folder).
JsonSerializerSettings settings = config.Formatters.JsonFormatter.SerializerSettings;
settings.ContractResolver = new CustomResolver();
Another Approach
Another possible approach uses a custom JsonConverter to handle the serialization of the PagedData class specifically instead using the more general "resolver + attributes" approach presented above. The converter approach requires that there be another property on your PagedData class which specifies the JSON name to use for the enumerable Data property. You could either pass this name in the PagedData constructor or set it separately, as long as you do it before serialization time. The converter will look for that name and use it when writing out JSON for the enumerable property.
Here is the code for the converter:
public class PagedDataConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(PagedData<>);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
Type type = value.GetType();
var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
string dataPropertyName = (string)type.GetProperty("DataPropertyName", bindingFlags).GetValue(value);
if (string.IsNullOrEmpty(dataPropertyName))
{
dataPropertyName = "Data";
}
JObject jo = new JObject();
jo.Add(dataPropertyName, JArray.FromObject(type.GetProperty("Data").GetValue(value)));
foreach (PropertyInfo prop in type.GetProperties().Where(p => !p.Name.StartsWith("Data")))
{
jo.Add(prop.Name, new JValue(prop.GetValue(value)));
}
jo.WriteTo(writer);
}
public override bool CanRead
{
get { return false; }
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
To use this converter, first add a string property called DataPropertyName to your PagedData class (it can be private if you like), then add a [JsonConverter] attribute to the class to tie it to the converter:
[JsonConverter(typeof(PagedDataConverter))]
public class PagedData<T>
{
private string DataPropertyName { get; set; }
public IEnumerable<T> Data { get; private set; }
...
}
And that's it. As long as you've set the DataPropertyName property, it will be picked up by the converter on serialization.
Fiddle: https://dotnetfiddle.net/8E8fEE

UPD Sep 2020: #RyanHarlich pointed that proposed solution doesn't work out of the box. I found that Newtonsoft.Json doesn't initialize getter-only properties in newer versions, but I'm pretty sure it did ATM I wrote this answer in 2016 (no proofs, sorry :).
A quick-n-dirty solution is to add public setters to all properties ( example in dotnetfiddle ). I encourage you to find a better solution that keeps read-only interface for data objects. I haven't used .Net for 3 years, so cannot give you that solution myself, sorry :/
Another option with no need to play with json formatters or use string replacements - only inheritance and overriding (still not very nice solution, imo):
public class MyUser { }
public class MyItem { }
// you cannot use it out of the box, because it's abstract,
// i.e. only for what's intended [=implemented].
public abstract class PaginatedData<T>
{
// abstract, so you don't forget to override it in ancestors
public abstract IEnumerable<T> Data { get; }
public int Count { get; }
public int CurrentPage { get; }
public int Offset { get; }
public int RowsPerPage { get; }
public int? PreviousPage { get; }
public int? NextPage { get; }
}
// you specify class explicitly
// name is clear,.. still not clearer than PaginatedData<MyUser> though
public sealed class PaginatedUsers : PaginatedData<MyUser>
{
// explicit mapping - more agile than implicit name convension
[JsonProperty("Users")]
public override IEnumerable<MyUser> Data { get; }
}
public sealed class PaginatedItems : PaginatedData<MyItem>
{
[JsonProperty("Items")]
public override IEnumerable<MyItem> Data { get; }
}

Here is a solution that doesn't require any change in the way you use the Json serializer. In fact, it should also work with other serializers. It uses the cool DynamicObject class.
The usage is just like you wanted:
var usersPagedData = new PagedData<User>("Users");
....
public class PagedData<T> : DynamicObject
{
private string _name;
public PagedData(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
_name = name;
}
public IEnumerable<T> Data { get; private set; }
public int Count { get; private set; }
public int CurrentPage { get; private set; }
public int Offset { get; private set; }
public int RowsPerPage { get; private set; }
public int? PreviousPage { get; private set; }
public int? NextPage { get; private set; }
public override IEnumerable<string> GetDynamicMemberNames()
{
yield return _name;
foreach (var prop in GetType().GetProperties().Where(p => p.CanRead && p.GetIndexParameters().Length == 0 && p.Name != nameof(Data)))
{
yield return prop.Name;
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (binder.Name == _name)
{
result = Data;
return true;
}
return base.TryGetMember(binder, out result);
}
}

The following is another solution tested in .NET Standard 2.
public class PagedResult<T> where T : class
{
[JsonPropertyNameBasedOnItemClassAttribute]
public List<T> Results { get; set; }
[JsonProperty("count")]
public long Count { get; set; }
[JsonProperty("total_count")]
public long TotalCount { get; set; }
[JsonProperty("current_page")]
public long CurrentPage { get; set; }
[JsonProperty("per_page")]
public long PerPage { get; set; }
[JsonProperty("pages")]
public long Pages { get; set; }
}
I am using Humanizer for pluralization.
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (member.GetCustomAttribute<JsonPropertyNameBasedOnItemClassAttribute>() != null)
{
Type[] arguments = property.DeclaringType.GenericTypeArguments;
if(arguments.Length > 0)
{
string name = arguments[0].Name.ToString();
property.PropertyName = name.ToLower().Pluralize();
}
return property;
}
return base.CreateProperty(member, memberSerialization);
}

There's a package called SerializationInterceptor. Here's the GitHub link: https://github.com/Dorin-Mocan/SerializationInterceptor/wiki. You can also install the package using Nuget Package Manager.
The example from below uses Syste.Text.Json for serialization. You can use any other serializer(except Newtonsoft.Json). For more info on why Newtonsoft.Json not allowed, please refer to GitHub documentation.
You can create an interceptor
public class JsonPropertyNameInterceptorAttribute : InterceptorAttribute
{
public JsonPropertyNameInterceptorAttribute(string interceptorId)
: base(interceptorId, typeof(JsonPropertyNameAttribute))
{
}
protected override void Intercept(in AttributeParams originalAttributeParams, object context)
{
string theNameYouWant;
switch (InterceptorId)
{
case "some id":
theNameYouWant = (string)context;
break;
default:
return;
}
originalAttributeParams.ConstructorArgs.First().ArgValue = theNameYouWant;
}
}
And put the interceptor on the Data prop
public class PagedData<T>
{
[JsonPropertyNameInterceptor("some id")]
[JsonPropertyName("during serialization this value will be replaced with the one passed in context")]
public IEnumerable<T> Data { get; private set; }
public int Count { get; private set; }
public int CurrentPage { get; private set; }
public int Offset { get; private set; }
public int RowsPerPage { get; private set; }
public int? PreviousPage { get; private set; }
public int? NextPage { get; private set; }
}
And then you can serialize the object like this
var serializedObj = InterceptSerialization(
obj,
objType,
(o, t) =>
{
return JsonSerializer.Serialize(o, t, new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.Preserve });
},
context: "the name you want");
Hope this will be of use to you.

have a look here:
How to rename JSON key
Its not done during serialization but with a string operation.
Not very nice (in my eyes) but at least a possibility.
Cheers Thomas

Related

System.Text.Json Deserialization using constructor

I am using System.Text.Json for deserialization.
I want to use the constructor in SerialNo(string serialNo) to build my object.
public class SerialNo
{
[JsonConstructor]
public SerialNo(string serialNo)
{
if (serialNo == null) throw new ArgumentNullException(nameof(serialNo));
if (string.IsNullOrWhiteSpace(serialNo)) throw new Exception("My exception text");
Value = serialNo.Trim('0');
}
public string Value { get; set; }
}
public class Item
{
public SerialNo SerialNo { get; set; }
public string AffiliationOrgCode { get; set; }
}
public class Root
{
public List<Item> Item { get; set; }
}
public class DeserializationTestsWithSystemTextJson
{
private const string JsonString = #"
{
""item"": [
{
""serialNo"": ""000000000002200878"",
""affiliationOrgCode"": ""OrgCode1""
},
{
""serialNo"": ""000000000002201675"",
""affiliationOrgCode"": ""OrgCode1""
}
]
}
";
[Fact]
public void Simple_Deserialization_With_SystemTextJson()
{
var options = new JsonSerializerOptions(JsonSerializerDefaults.Web);
var deserializedClass = JsonSerializer.Deserialize<Root>(JsonString, options);
Assert.NotNull(deserializedClass);
Assert.Equal("2201675", deserializedClass.Item[1].SerialNo.Value);
}
}
Fails with:
The JSON value could not be converted to JsonNetDeserialization.Test.WithSystemText.SerialNo. Path: $.item[0].serialNo | LineNumber: 3 | BytePositionInLine: 44.
Any ideas?
Since you are converting a string to a SerialNo, you need a custom converter. For example:
public class SerialNoConverter : JsonConverter<SerialNo>
{
public override SerialNo? Read(ref Utf8JsonReader reader, Type typeToConvert,
JsonSerializerOptions options)
{
var serialNo = reader.GetString();
return new SerialNo(serialNo);
}
public override void Write(Utf8JsonWriter writer, SerialNo value,
JsonSerializerOptions options)
{
// Left for OP if required
throw new NotImplementedException();
}
}
And to use it you can either add an attribute to your class:
public class Item
{
[JsonConverter(typeof(SerialNoConverter))]
public SerialNo SerialNo { get; set; }
public string AffiliationOrgCode { get; set; }
}
Or add the converter to your serialiser options:
options.Converters.Add(new SerialNoConverter());
Here is a running example.
You are able to use a constructor to deserialize JSON using System.Text.Json, contrary to what the marked answer says. Even Microsoft documents it: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/immutability?pivots=dotnet-7-0
There are a some drawbacks though:
All class/struct fields/properties must match the JSON property name exactly
All json properties must not be nested in a deeper JSON object
To deserialize JSON with a constructor, you just need to use [JsonConstructor]. Here's an example of deserializing this way:
JSON:
{
"Fp": 2.199,
"Pi": 3.14159,
"Str": "Hello World"
}
The deserialized class:
public class Dto
{
public double Fp { get; set; }
public double Pi { get; set; }
public string Str { get; set; }
[JsonConstructor]
public Dto(double fp, double pi, string str)
{
Fp = fp;
Pi = pi;
Str = str;
}
public override string ToString()
{
return $"{nameof(Fp)}: {Fp}, {nameof(Pi)}: {Pi}, {nameof(Str)}: {Str}";
}
}
Now to deserialize, you just include this expression: var dto = JsonSerializer.Deserialize<Dto>(Json); In the event you are trying to deserialize are custom type, you can include the [JsonConverter(...)] attribute over the custom type properties/fields in your deserialized class if the custom types do not already have a JsonConverter attribute for their class. Because the class properties use the exact name as in the Json, all other types are still deserialized properly and the custom type property will use the attributed custom converter. Here is an example of using a custom converter:
public class Dto
{
public double Fp { get; set; }
public double Pi { get; set; }
[JsonConverter(typeof(CustomStringConverter))] // This can be removed if the CustomString class already has a JsonConverter attribute
public CustomString Str { get; set; }
[JsonConstructor]
public Dto(double fp, double pi, CustomString str)
{
this.Fp = fp;
Pi = pi;
Str = str;
}
public override string ToString()
{
return $"{nameof(Fp)}: {Fp}, {nameof(Pi)}: {Pi}, {nameof(Str)}: {Str}";
}
}

How do I re-architect my model types to reduce code replication

I have 3 model types:
public class BankA_Transaction : BanKTransactionMetaData
{
public string GROUPName { get; set; }
public string ACC_ID { get; set; }
public string ACCOUNT_NO { get; set; }
}
public class BankB_Transaction : BanKTransactionMetaData
{
public string Name { get; set; }
public string ACC_ID { get; set; }
public string ACCOUNT_NO { get; set; }
}
public class BankC_Transaction : BanKTransactionMetaData
{
public string FullName { get; set; }
public string ACC_ID { get; set; }
public string ACCOUNT_NO { get; set; }
}
Note: The actual property lists are much longer
All of which inherit some fields needed when saving into the database.
public class BanKTransactionMetaData
{
public String BankName { get; set; }
}
These models get filled with records from a file sent by the bank and then saved to a database.
As part of this save I convert the records to JSON as that is required by the database.
public void SaveBankA(BankA bankA)
{
bankA.BankName = "Bank_A";
string jsonText = JsonConvert.SerializeObject(bankA_Transaction, Formatting.Indented);
Code for saving...
At the moment I have a different methods for SaveBankA, SaveBankA and SaveBankB.
It seems to me that this is code replication and that I should get all the models to inherit better in order to use a base type? instead of each named type.
I've read up on Abstract and Virtual classes as I suspect that's what I need but I can't work out how to plug it together.
I can't just use Object in SaveBankA as I need to add .BankName.
Is there a better architecture to reduce code replication?
Perhaps you need something like this?
In base service class:
protected void SaveBankTransaction(BankTransactionMetaData tran)
{
string jsonText = JsonConvert.SerializeObject(tran, Formatting.Indented);
// additional saving code
}
In child service classes:
public void SaveBankA(BankA bankA)
{
bankA.BankName = "Bank_A";
base.SaveBankTransaction(bankA);
}
Create a couple of interfaces, one for your meta data (IBankData) and one for your bank transaction details (IBankTransaction). The IBankData interface will maintain a reference to the IBankTransaction interface. This should also allow you to add additional banks when needed, e.g. Bank D.
public interface IBankData
{
string BankName { get; }
// ... additional bank meta data properties
// ...
IBankTransaction Transaction { get; set; }
}
public interface IBankTransaction
{
[JsonProperty("ACC_ID")]
string AccountId { get; set; }
[JsonProperty("ACCOUNT_NO")]
string AccountNumber { get; set; }
// ... additional shared bank transaction properties
// ...
}
FYI, I chose to use the JsonProperty attribute to control the name for the JSON key, this allows the class properties to be named according to best practices without affecting the JSON property names.
Next implement the interfaces for each bank you will be working with. In each bank add the additional properties that will only apply to each implementation, i.e. since the GroupName property is only used by BankA, this property will be added to the BankA class and not the interface. The same goes for any other bank specific properties.
Bank A
public class BankA : IBankData
{
public string BankName => "BankA";
public IBankTransaction Transaction { get; set; }
}
public class BankATransaction : IBankTransaction
{
// Bank A specific properties
[JsonProperty("GROUPName")]
public string GroupName { get; set; }
// ... additional Bank A specific properties
// ...
// interface implemented properties
public string AccountId { get; set; }
public string AccountNumber { get; set; }
}
Bank B
public class BankB : IBankData
{
public string BankName => "BankB";
public IBankTransaction Transaction { get; set; }
}
public class BankBTransaction : IBankTransaction
{
// Bank B specific properties
public string Name { get; set; }
// ... additional Bank B specific properties
// ...
// interface implemented properties
public string AccountId { get; set; }
public string AccountNumber { get; set; }
}
Bank C
public class BankC : IBankData
{
public string BankName => "BankC";
public IBankTransaction Transaction { get; set; }
}
public class BankCTransaction : IBankTransaction
{
// Bank B specific properties
public string FullName { get; set; }
// ... additional Bank B specific properties
// ...
// interface implemented properties
public string AccountId { get; set; }
public string AccountNumber { get; set; }
}
JsonConverter
Since the IBankTransaction is a property within the IBankData this will change your JSON structer. You may not want this, to retain your structure, a JsonConverter can be implemented on the IBankData interface. This will remove the Transaction object in the JSON and move the child properties under the JSON root.
public class BankJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
JToken t = JToken.FromObject(value);
if (t.Type != JTokenType.Object)
{
t.WriteTo(writer);
}
else
{
JObject o = (JObject)t;
JProperty transactionProperty = o.Properties().FirstOrDefault(p => p.Name == "Transaction");
o.Remove("Transaction");
JToken token = transactionProperty;
foreach (JToken ct in token.Children())
{
foreach (var prop in JProperty.FromObject(ct))
{
o.Add(prop);
}
}
serializer.Serialize(writer, o);
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException("Unnecessary because CanRead is false. The type will skip the converter.");
}
public override bool CanRead => false;
public override bool CanConvert(Type objectType)
{
return objectType.GetInterfaces().Contains(typeof(IBankData));
}
}
Usage
For the usage example I've created a few test functions to prep the data and added SaveBank method that you can relocate in your actual code as it would make sense for your solution.
class Program
{
static void Main(string[] args)
{
string bankATransJson = GetBankATestJsonInput();
BankATransaction bankATransaction = JsonConvert.DeserializeObject<BankATransaction>(bankATransJson);
BankA bankA = new BankA();
bankA.Transaction = bankATransaction;
Console.WriteLine(SaveBank(bankA));
// output:
// {
// "BankName": "BankA",
// "GROUPName": "g54321",
// "ACC_ID": "A01",
// "ACCOUNT_NO": "A1111"
// }
string bankBInputJson = GetBankBTestJsonInput();
BankBTransaction bankBTransInput = JsonConvert.DeserializeObject<BankBTransaction>(bankBInputJson);
BankB bankB = new BankB();
bankB.Transaction = bankBTransInput;
Console.WriteLine(SaveBank(bankB));
// output:
// {
// "BankName": "BankB",
// "ACC_ID": "B02",
// "ACCOUNT_NO": "B2222",
// "Name": "Bank_Of_B
// }
string bankCInputJson = GetBankCTestJsonInput();
BankCTransaction bankCTransInput = JsonConvert.DeserializeObject<BankCTransaction>(bankCInputJson);
BankC bankC = new BankC();
bankC.Transaction = bankCTransInput;
Console.WriteLine(SaveBank(bankC));
// output:
// {
// "BankName": "BankC",
// "ACC_ID": "C03",
// "ACCOUNT_NO": "C3333",
// "FullName": "C Bank"
// }
}
public static string SaveBank(IBankData bankData)
{
// when calling the serialize object method, we pass our BankJsonConverter
string jsonText = JsonConvert.SerializeObject(bankData, Formatting.Indented, new BankJsonConverter());
// this example just returns the JSON text
// but you would implement your save logic as needed
return jsonText;
}
private static string GetBankATestJsonInput()
{
var obj = new { ACC_ID = "A01", ACCOUNT_NO = "A1111", GROUPName = "g54321" };
return JsonConvert.SerializeObject(obj);
}
private static string GetBankBTestJsonInput()
{
var obj = new { ACC_ID = "B02", ACCOUNT_NO = "B2222", Name = "Bank_Of_B" };
return JsonConvert.SerializeObject(obj);
}
private static string GetBankCTestJsonInput()
{
var obj = new { ACC_ID = "C03", ACCOUNT_NO = "C3333", FullName = "C Bank" };
return JsonConvert.SerializeObject(obj);
}
}

Serializing a collection of view models with overridden Equals method

Trying to serialize a collection of a custom type with an overloaded Equals(object obj) method. I am using Newtonsoft.Json.JsonConvert.SerializeObject(object value) to achieve this.
This is my abstract base view model from which the view model in question inherits:
public abstract class BaseCollectibleViewModel
{
protected abstract bool CompareParameters(object item);
protected abstract List<int> GetParameters();
public override bool Equals(object obj)
{
if (CompareParameters(obj))
{
return true;
}
return false;
}
public override int GetHashCode()
{
int hash = 13;
foreach (var parameter in GetParameters())
{
hash = (hash * 7) + parameter.GetHashCode();
}
return hash;
}
public static bool operator ==(BaseCollectibleViewModel a, BaseCollectibleViewModel b)
{
if (a.Equals(b))
{
return true;
}
return false;
}
public static bool operator !=(BaseCollectibleViewModel a, BaseCollectibleViewModel b)
{
if (a.Equals(b))
{
return false;
}
return true;
}
}
This is the actual view model:
public class ImagesViewModel : BaseCollectibleViewModel, ISourceImage
{
public string Name { get; private set; }
public string Type { get; private set; }
[ScriptIgnore]
public Stream Content { get; private set; }
[ScriptIgnore]
private HttpPostedFileBase _file;
[ScriptIgnore]
public HttpPostedFileBase File
{
get
{
return _file;
}
set
{
_file = value;
Name = File.FileName;
Type = File.ContentType;
Content = new MemoryStream();
File.InputStream.CopyTo(Content);
}
}
protected override bool CompareParameters(object obj)
{
var temp = obj as ImagesViewModel;
if(temp == null)
{
return false;
}
return
(Name == temp.Name &&
Type == temp.Type);
}
protected override List<int> GetParameters()
{
return new List<int>()
{
Name.GetHashCode(),
Type.GetHashCode()
};
}
}
Notice the ScriptIgnore attributes. I even have one on the private field. The program breaks on the == operator of the base class because both of the arguments that get passed are null.
This is the serializing code:
[HttpPost]
public string GetSessionImages()
{
var imagesInSession = _imagesSessionService.GetCollection();
return JsonConvert.SerializeObject(imagesInSession, Formatting.Indented);
}
Also this:
The screenshot is showing the implementation of the abstract CompareParameters(object obj) method on the inheriting view model. That stream is the Content property stream, I have checked. Why is this happening?
EDIT: When not overriding Equals I get a JsonSerializationException stating:
{"Error getting value from 'ReadTimeout' on
'System.IO.MemoryStream'."}
EDIT 2: Per dbc's comment I have replaced the attribute [ScriptIgnore] with [JsonIgnore] and the code worked to an extent.
However, I had to comment out the operator implementations because the '==' operator would be passed a null value as the BaseCollectibleViewModel b argument.
Since you are using json.net, you must mark members to ignore with [JsonIgnore]:
using Newtonsoft.Json;
public class ImagesViewModel : BaseCollectibleViewModel, ISourceImage
{
public string Name { get; private set; }
public string Type { get; private set; }
[ScriptIgnore]
[JsonIgnore]
public Stream Content { get; private set; }
[ScriptIgnore]
[JsonIgnore]
public HttpPostedFileBase File { get { ... } set { ... } }
It is not necessary to mark entirely private members with [JsonIgnore] as these are not serialized by default by Json.NET.
Alternatively, if you do not want your models to have a dependency on Json.NET, you could use conditional property serialization to unconditionally suppress the same members:
public class ImagesViewModel : BaseCollectibleViewModel, ISourceImage
{
public string Name { get; private set; }
public string Type { get; private set; }
[ScriptIgnore]
public Stream Content { get; private set; }
public bool ShouldSerializeContent() { return false; }
[ScriptIgnore]
public HttpPostedFileBase File { get { ... } set { ... } }
public bool ShouldSerializeFile() { return false; }
Note that the ShouldSerializeXXX() conditional serialization pattern is also respected by other serializers including XmlSerializer, as explained in ShouldSerialize*() vs *Specified Conditional Serialization Pattern - a side-effect which may be desirable, or not.
(Incidentally, you might want to check that you are not double-serializing your data as shown in JSON.NET Parser *seems* to be double serializing my objects.)

How to force JSON serialization to include type information for a polymorphic System.Enum member?

I am using JSON serialization and deserialization for serialize/deserialize the storage class of my big application.
some where in my application, I need to hold the enums of different enumsType in an Enum or sum times i will need to hold the different classes inherited from a parent class to a variable of type of parent class. please look at the below code which demonstrate an example for an enum. in these situation, the serialization gets error especially for enums and cannot find the enum because the type of variable in Enum. for example in the below sample code the inputEnum is of type Enum and can get enums of Enum1 and Enum2. but in deserialization the Json brings error that cannot convert int64 to type of Enum.
Now I need the JSON to hold the original type of the variables to deserialize them. for example in inputenum=Enum1.hi, the type to be hold as Enum1 instead of Enum that is occurring now.
Please give your solutions.
public enum Enum1
{
hi=0,
hello
}
public enum Enum2
{
by = 0,
goodbye
}
public class TUnitClass
{
public string Id { set; get; }
public string Name { set; get; }
public Enum inputenum { set; get; }
public string Comment { set; get; }
public string displayingString { set; get; }
}
private void Form1_Load(object sender, EventArgs e)
{
List<TUnitClass> cls1=new List<TUnitClass>()
{
new TUnitClass() {inputenum = Enum2.goodbye},
new TUnitClass() {inputenum = Enum2.by},
new TUnitClass() {inputenum = Enum1.hello},
new TUnitClass() {inputenum = Enum1.hi},
new TUnitClass() {inputenum = Enum2.goodbye},
};
string strSerialized = JsonConvert.SerializeObject(cls1);
List<TUnitClass> cls2 = JsonConvert.DeserializeObject<List<TUnitClass>>(strSerialized,new JsonSerializerSettings() {Error = ErrorOnDeserialization});
}
private void ErrorOnDeserialization(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs e)
{
}
Update
I have attempted to implement the solution from Deserialize specific enum into system.enum in Json.Net. Type information is correctly written to the JSON file during serialization, however during deserialization an exception is thrown:
Newtonsoft.Json.JsonSerializationException occurred
Message="Type specified in JSON 'MTC.Utility.UnitConvertor.TypeWrapper`1[[MTC.Utility.UnitConvertor.EAcceleration, MTC.Utility.UnitConvertor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], MTC.Utility.UnitConvertor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not compatible with 'System.Enum, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Path 'listOfUnitSystems[0].UnitsList[0].Unit.$type', line 17, position 269."
Source="Newtonsoft.Json"
StackTrace:
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.ResolveTypeName(JsonReader reader, Type& objectType, JsonContract& contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, String qualifiedTypeName) in C:\Development\Releases\Json\Working\Newtonsoft.Json\Working-Signed\Src\Newtonsoft.Json\Serialization\JsonSerializerInternalReader.cs:line 814
InnerException:
Here is the updated code:
public abstract class TypeWrapper
{
protected TypeWrapper() { }
[JsonIgnore]
public abstract object ObjectValue { get; }
public static TypeWrapper CreateWrapper<T>(T value)
{
if (value == null)
return new TypeWrapper<T>();
var type = value.GetType();
if (type == typeof(T))
return new TypeWrapper<T>(value);
// Return actual type of subclass
return (TypeWrapper)Activator.CreateInstance(typeof(TypeWrapper<>).MakeGenericType(type), value);
}
}
public sealed class TypeWrapper<T> : TypeWrapper
{
public TypeWrapper() : base() { }
public TypeWrapper(T value)
: base()
{
this.Value = value;
}
public override object ObjectValue { get { return Value; } }
public T Value { get; set; }
}
public class TUnitClass
{
public string Id { set; get; }
public string Name { set; get; }
public EQuantities Quantity { set; get; }
[JsonIgnore]
public System.Enum Unit { get; set; }
[JsonProperty("Unit", TypeNameHandling = TypeNameHandling.All)]
TypeWrapper UnitValue
{
get
{
return Unit == null ? null : TypeWrapper.CreateWrapper(Unit);
}
set
{
if (value == null || value.ObjectValue == null)
Unit = null;
else
Unit = (Enum)value.ObjectValue;
}
}
public string Comment { set; get; }
public string displayingString { set; get; }
public TUnitClass(string id, EQuantities quantity,Enum unit, string comment)
{
Id = id;
Name = quantity.ToString();
Quantity = quantity;
Unit = unit;
Comment = comment;
FieldInfo fi = unit.GetType().GetField(unit.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
displayingString= attributes[0].Description;
}
}
Update 2
Finally, If I have an Enum[] property instead of Enum, how can I behave with this problem?
The reason the solution from question 31351262 does not work is that your type TUnitClass does not have a default constructor. Instead, it has a single parameterized constructor. In cases like this, Json.NET will invoke that constructor, matching JSON objects to constructor arguments by name, modulo case. (For details, see this answer.) And unfortunately your constructor takes an abstract System.Enum as its unit argument:
public TUnitClass(string id, EQuantities quantity, Enum unit, string comment)
{
}
Json.NET will deserialize the surrogate TypeWrapper<TEnum> correctly but then try to cast it to a System.Enum in order to call the constructor, and fail, throwing the exception you are seeing.
The solution is to add a constructor that accepts a surrogate TypeWrapper unit value, and mark that constructor with [JsonConstructor]. It can be private as long as it is marked with [JsonConstructor]. The following should work:
public class TUnitClass
{
[JsonConstructor]
TUnitClass(string id, EQuantities quantity, TypeWrapper<Enum> unit, string comment)
: this(id, quantity, unit.Value(), comment)
{
}
public TUnitClass(string id, EQuantities quantity, Enum unit, string comment)
{
Id = id;
Name = quantity.ToString();
Quantity = quantity;
Unit = unit;
Comment = comment;
FieldInfo fi = unit.GetType().GetField(unit.ToString());
DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
displayingString = attributes[0].Description;
}
public string Id { set; get; }
public string Name { set; get; }
public EQuantities Quantity { set; get; }
[JsonIgnore]
public System.Enum Unit { get; set; }
[JsonProperty("Unit", TypeNameHandling = TypeNameHandling.All)]
TypeWrapper<Enum> UnitSurrogate
{
get
{
return Unit == null ? null : TypeWrapper<Enum>.CreateWrapper(Unit);
}
set
{
Unit = value.Value();
}
}
public string Comment { set; get; }
public string displayingString { set; get; }
public TUnitClass Copy()
{
TUnitClass copiedUnitClass=new TUnitClass(Id,Quantity,Unit,Comment);
return copiedUnitClass;
}
}
public abstract class TypeWrapper<TBase>
{
protected TypeWrapper() { }
[JsonIgnore]
public abstract TBase BaseValue { get; }
public static TypeWrapper<TBase> CreateWrapper<TDerived>(TDerived value) where TDerived : TBase
{
if (value == null)
return null;
var type = value.GetType();
if (type == typeof(TDerived))
return new TypeWrapper<TDerived, TBase>(value);
// Return actual type of subclass
return (TypeWrapper<TBase>)Activator.CreateInstance(typeof(TypeWrapper<,>).MakeGenericType(type, typeof(TBase)), value);
}
}
public static class TypeWrapperExtensions
{
public static TBase Value<TBase>(this TypeWrapper<TBase> wrapper)
{
if (wrapper == null || wrapper.BaseValue == null)
return default(TBase);
return wrapper.BaseValue;
}
}
public sealed class TypeWrapper<TDerived, TBase> : TypeWrapper<TBase> where TDerived : TBase
{
public TypeWrapper() : base() { }
public TypeWrapper(TDerived value)
: base()
{
this.Value = value;
}
public override TBase BaseValue { get { return Value; } }
public TDerived Value { get; set; }
}
TypeNameAssemblyFormat = FormatterAssemblyStyle.Full should no longer be necessary.
Note I modified the linked answer to add type safety to ensure the serialized type is in fact a System.Enum, which should increase security by preventing unexpected types during deserialization. See TypeNameHandling caution in Newtonsoft Json for a general discussion of TypeNameHandling security.
Update
If I have a Enum[] instead of Enum, how can I behave with this problem?
You would need to use a surrogate array of TypeWrapper<Enum> objects, like so:
public class TUnitArrayClass
{
[JsonConstructor]
TUnitArrayClass(TypeWrapper<Enum>[] units)
: this(units == null ? null : units.Select(s => s.Value()).ToArray())
{
}
public TUnitArrayClass(IEnumerable<System.Enum> units)
{
this.Units = (units ?? Enumerable.Empty<System.Enum>()).ToArray();
}
[JsonIgnore]
public System.Enum[] Units { get; set; }
[JsonProperty("Unit", TypeNameHandling = TypeNameHandling.All)]
TypeWrapper<Enum> [] UnitsSurrogate
{
get
{
return Units == null ? null : Units.Select(u => TypeWrapper<Enum>.CreateWrapper(u)).ToArray();
}
set
{
if (value == null)
Units = null;
else
Units = value.Select(s => s.Value()).ToArray();
}
}
}

How to exclude property from Json Serialization

I have a DTO class which I Serialize
Json.Serialize(MyClass)
How can I exclude a public property of it?
(It has to be public, as I use it in my code somewhere else)
If you are using Json.Net attribute [JsonIgnore] will simply ignore the field/property while serializing or deserialising.
public class Car
{
// included in JSON
public string Model { get; set; }
public DateTime Year { get; set; }
public List<string> Features { get; set; }
// ignored
[JsonIgnore]
public DateTime LastModified { get; set; }
}
Or you can use DataContract and DataMember attribute to selectively serialize/deserialize properties/fields.
[DataContract]
public class Computer
{
// included in JSON
[DataMember]
public string Name { get; set; }
[DataMember]
public decimal SalePrice { get; set; }
// ignored
public string Manufacture { get; set; }
public int StockCount { get; set; }
public decimal WholeSalePrice { get; set; }
public DateTime NextShipmentDate { get; set; }
}
Refer http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size for more details
If you are using System.Web.Script.Serialization in the .NET framework you can put a ScriptIgnore attribute on the members that shouldn't be serialized. See the example taken from here:
Consider the following (simplified) case:
public class User {
public int Id { get; set; }
public string Name { get; set; }
[ScriptIgnore]
public bool IsComplete
{
get { return Id > 0 && !string.IsNullOrEmpty(Name); }
}
}
In this case, only the Id and the Name properties will be serialized, thus the resulting JSON object would look like this:
{ Id: 3, Name: 'Test User' }
PS. Don't forget to add a reference to "System.Web.Extensions" for this to work
Sorry I decided to write another answer since none of the other answers are copy-pasteable enough.
If you don't want to decorate properties with some attributes, or if you have no access to the class, or if you want to decide what to serialize during runtime, etc. etc. here's how you do it in Newtonsoft.Json
//short helper class to ignore some properties from serialization
public class IgnorePropertiesResolver : DefaultContractResolver
{
private readonly HashSet<string> ignoreProps;
public IgnorePropertiesResolver(IEnumerable<string> propNamesToIgnore)
{
this.ignoreProps = new HashSet<string>(propNamesToIgnore);
}
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (this.ignoreProps.Contains(property.PropertyName))
{
property.ShouldSerialize = _ => false;
}
return property;
}
}
Usage
JsonConvert.SerializeObject(YourObject, new JsonSerializerSettings()
{ ContractResolver = new IgnorePropertiesResolver(new[] { "Prop1", "Prop2" }) });
Note: make sure you cache the ContractResolver object if you decide to use this answer, otherwise performance may suffer.
I've published the code here in case anyone wants to add anything
https://github.com/jitbit/JsonIgnoreProps
You can use [ScriptIgnore]:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
[ScriptIgnore]
public bool IsComplete
{
get { return Id > 0 && !string.IsNullOrEmpty(Name); }
}
}
In this case the Id and then name will only be serialized
If you are not so keen on having to decorate code with Attributes as I am, esp when you cant tell at compile time what will happen here is my solution.
Using the Javascript Serializer
public static class JsonSerializerExtensions
{
public static string ToJsonString(this object target,bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
if(ignoreNulls)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(target.GetType(), true) });
}
return javaScriptSerializer.Serialize(target);
}
public static string ToJsonString(this object target, Dictionary<Type, List<string>> ignore, bool ignoreNulls = true)
{
var javaScriptSerializer = new JavaScriptSerializer();
foreach (var key in ignore.Keys)
{
javaScriptSerializer.RegisterConverters(new[] { new PropertyExclusionConverter(key, ignore[key], ignoreNulls) });
}
return javaScriptSerializer.Serialize(target);
}
}
public class PropertyExclusionConverter : JavaScriptConverter
{
private readonly List<string> propertiesToIgnore;
private readonly Type type;
private readonly bool ignoreNulls;
public PropertyExclusionConverter(Type type, List<string> propertiesToIgnore, bool ignoreNulls)
{
this.ignoreNulls = ignoreNulls;
this.type = type;
this.propertiesToIgnore = propertiesToIgnore ?? new List<string>();
}
public PropertyExclusionConverter(Type type, bool ignoreNulls)
: this(type, null, ignoreNulls){}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { this.type })); }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var result = new Dictionary<string, object>();
if (obj == null)
{
return result;
}
var properties = obj.GetType().GetProperties();
foreach (var propertyInfo in properties)
{
if (!this.propertiesToIgnore.Contains(propertyInfo.Name))
{
if(this.ignoreNulls && propertyInfo.GetValue(obj, null) == null)
{
continue;
}
result.Add(propertyInfo.Name, propertyInfo.GetValue(obj, null));
}
}
return result;
}
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException(); //Converter is currently only used for ignoring properties on serialization
}
}
If you are using System.Text.Json then you can use [JsonIgnore].
FQ: System.Text.Json.Serialization.JsonIgnoreAttribute
Official Microsoft Docs: JsonIgnoreAttribute
As stated here:
The library is built-in as part of the .NET Core 3.0 shared framework.
For other target frameworks, install the System.Text.Json NuGet
package. The package supports:
.NET Standard 2.0 and later versions
.NET Framework 4.6.1 and later versions
.NET Core 2.0, 2.1, and 2.2
For C# 9's records it's [property: JsonIgnore]
using System.Text.Json.Serialization;
public record R(
string Text2
[property: JsonIgnore] string Text2)
For the classic style it's still just [JsonIgnore].
using System.Text.Json.Serialization;
public record R
{
public string Text {get; init; }
[JsonIgnore]
public string Text2 { get; init; }
}
You can also use the [NonSerialized] attribute
[Serializable]
public struct MySerializableStruct
{
[NonSerialized]
public string hiddenField;
public string normalField;
}
From the MS docs:
Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.
If you're using Unity for example (this isn't only for Unity) then this works with UnityEngine.JsonUtility
using UnityEngine;
MySerializableStruct mss = new MySerializableStruct
{
hiddenField = "foo",
normalField = "bar"
};
Debug.Log(JsonUtility.ToJson(mss)); // result: {"normalField":"bar"}
Add System.Text.Json Version for dotnet core
For compile time, add [JsonIgnore] as suggested in the above answer.
For run time, JsonConverter needs to be added into the options.
First, create a JsonConverter for the type you want to exclude, for example ICollection<LabMethod> below
public class LabMethodConverter : JsonConverter<ICollection<LabMethod>>
{
public override ICollection<LabMethod> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
//deserialize JSON into a ICollection<LabMethod>
return null;
}
public override void Write(Utf8JsonWriter writer, ICollection<LabMethod> value, JsonSerializerOptions options)
{
//serialize a ICollection<LabMethod> object
writer.WriteNullValue();
}
}
Then add to options when you serialize Json
var options = new JsonSerializerOptions();
options.Converters.Add(new LabMethodConverter());
var new_obj = Json(new { rows = slice, total = count }, options);

Categories