Serializing an object frequently whenever there is a value change in properties - c#

I want to serialize an object whenever there is a change in the property value. Currently, INotifyPropertyChanged is not implemented in the class. What is the best practice to serialize the object frequently? Serialization should not hamper the application's performance. Please suggest NuGet packages if they can handle serializing the object frequently

Kindly Check Newtonsoft.Json
var jsonString = JsonConvert.SerializeObject(model);

Related

Does "NullValueHandling.Ignore" only works with POCOs?

I have api calls that return expando object & dynamic objects. Even though I have NullValueHandling set to IgnoreNulls, nulls are still sent back in the resulting json. I have tested it with my other calls that return POCO objects, and they function correctly (omitting null value fields). Is there a way around this?
I was thinking of trying to convert the expando\dynamic objects to something that that the serializer could process the same way it does POCO object results, but I don't know what that would be.
I tried manually serializing the object and then de-serializing it into a JSONArrayObject before it gets to the final Serialization in the MVC middleware, but that didn't work.
Also, I can't just create a POCO for these objects, because they are the result of "Data Shaping" i.e. the user sends in the fields they want to receive in the object, and then we take the resulting POCO, and turn it into an expando object with only the fields they requested.

How to get and deserialize value created with RedisOutputCacheProvider?

I'm using Microsoft.Web.Redis.RedisOutputCacheProvider for output caching in Redis. The task is to retrieve manually value from the Redis database and deserialize value for further processing the original HTML.
I tried StackExchange.Redis.IDatabase - can get value by key with StringGet() method, but the problem is that it's serialized. Any thoughts regarding above ?
That's because RedisOutputCacheProvider by default, serializes in a binary format provided by the BinaryFormatter class.
So you need to deserialize it in the same way OR use a custom serialization method on RedisOutputCacheProvider.
Check its configuration wiki with the instructions to use a custom serializer.

How to serialize an object that has a constantly updated collection

I have a cache service that holds multiple Price objects which are updated as new price deltas arrive, sometimes multiple times a second.
Each object holds it's various prices in a collection assigned to an ID. If someone subscribes to a particular price I need to serialize the latest price object into JSON each time a new price arrives in order to send it over RMQ. The problem I am having is that in some cases I receive the following error message while serializing because a new price has arrived and updated the collection on the object during the serialization of the previous.
"Collection was modified; enumeration operation may not execute."
I've tried various ways of serializing the object (it needs to be as fast as possible) but I still get the same issue.
What would be the best and most efficient way of solving this so I can serialize even if the object changes.
The simplified objects are:
//This is the collection on an object that holds the prices which are being updated
public ConcurrentDictionary<Id, Prices> Asset{ get; set; }
//Class that holds the ever updating prices
[Serializable]
public class Prices
{
public Prices()
{
Prices1 = new List<PriceVolume>();
Prices2 = new List<PriceVolume>();
}
}
thanks in advance!
Instead of serializing the actual object you pull from the concurrent dictionary you should create a deep copy of it and serialize the copy. unfortunately you will still have to put the code to get the copy inside a mutex. The ConcurrentDic is only protecting you from having an item changed or deleted while you are retrieving it, it does not protect the object from manipulation after you have retrieved your reference to it.
You could probably benefit from locking the element while you are serializing it.
Locking prevents other threads from modifying the element while you are inside the lock.
This will make the operations trying to change the prices wait until you are done serializing it to modify them.
[Serializable]
public class Prices
{
public string Serialize()
{
lock (this)
{
// logic for serilization here
}
}
}
Just a thought, but how about looking into Serialization Callbacks (some refer to this as Serialization Hooks) and Implementing the ISerializable Interface. You seem to need more fine-grained control over the serialization of your object. Have a look at this link:
Custom Serialization
Look at the following
OnDeserializingAttribute (Before deserialization)
OnDeserializedAttribute (After deserialization)
OnSerializingAttribute (Before serialization)
OnSerializedAttribute (After serialization)
Also have a look at this link:
Version Tolerant Serialization
You can consider if the object warrants the use of the OptionalFieldAttribute or NonSerializedAttribute on certain fields to control if they need to be serialized or optionally serialized. Just be wary of the use of the NonSerializedAttribute. Have a look at the best practices mentioned in the article (reproduced here for reference):
To ensure proper versioning behavior, follow these rules when modifying a type from version to version:
Never remove a serialized field
Never apply the NonSerializedAttribute attribute to a field if the attribute was not applied to the field in the previous version
Never change the name or the type of a serialized field
When adding a new serialized field, apply the OptionalFieldAttribute attribute
When removing a NonSerializedAttribute attribute from a field (that was not serializable in a previous version), apply the OptionalFieldAttribute attribute
For all optional fields, set meaningful defaults using the serialization callbacks unless 0 or null as defaults are acceptable
To ensure that a type will be compatible with future serialization engines, follow these guidelines:
Always set the VersionAdded property on the OptionalFieldAttribute attribute correctly
Avoid branched versioning

NewtonSoft.Json error

Hi I'm quite new to C# and I'm trying to make a text editor that saves and loads Plaintext formats. I've used NewtonSoft.Json NuGet package, but I'm getting an error. I've stated a string called textToLoad, which is set to a JsonConvert.DeserializeObject. Only thing is, it says it can't convert an object to a string! I tried toString(); but it still had the same error.
It is kind of hard without the code. The process of serializing and deserializing is pretty straight forward using Json.Net. So this is an example from their documentation:
YourType yourObject= new YourType();
yourObject.Property="something";
string output = JsonConvert.SerializeObject(yourObject);
//For some reason you want this to be string, but is the type you serialized in the first place
YourType textToLoad= JsonConvert.DeserializeObject<YourType>(output);
This outlines the basic works of serializing and deserializing. But we don't really know the details of your implementation.
Hope it helps.
You can't deserialize into a string like that. At simplest form you started with JSON in the form of:
{ value: "someString" }
If you want something out of it, you must deserialize and then get the value from it.
dynamic foo = JsonConvert.DeserializeObject<dynamic>(theJson);
var textToLoad = foo.value.ToString();
You must deserialize to something in order to inspect and get properties from it.
[Edit] - Perhaps I'm not understanding. But if you share code, I'll update my answer.

Serialize whole instance with child instances (class serialization) and save to file

I'm building a game with Unity3D. I have a class called GameInstance containing all the current game instance data in it. It contains multiple sub classes for instance the Player property would return a Player object.
Yet all objects are simple key/values objects, it's only data. Now I'd need to serialize all of this and save it to a file so I can reload it to restart the game where it left.
That's what I basically intent to do, maybe somebody would have a better suggestion but yet that's the most flexible option I found.
I used .NET XML object serialization in the past but it's been a while and I'd need to have a more direct advice on this. Should I serialize to XML or JSON for example?
TL;DR: I want to serialize a whole class with all its content with C#/.NET in a Unity3D project. How should I proceed?
Thanks!
I personally prefer json. If you're using json.NET this will be as simple as;
string json = JsonConvert.SerializeObject(MyObject);
or to compact it;
File.WriteAllText("./myfile", JsonConvert.SerializeObject(MyObject));
Then to deserialize you would just do;
MyObject obj = JsonConvert.DeserializeObject<MyObject>(File.ReadAllText("./myfile"));
EDIT: In response to the exception, you want to use this overload which allows you to change the serilization settings;
JsonConvert.SerializeObject(ResultGroups,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});

Categories

Resources