I haven't been able to find the answer to this anywhere, but when I try to serialize a struct or class with static or const member variables, they don't serialize by default. If I try to force serialization by setting MemberSerialization.OptIn
, I get an error.
ex.
[JsonObject(MemberSerialization.OptIn)]
public class Test
{
[JsonProperty]
public int x = 1;
[JsonProperty]
public static int y = 2;
}
If I try to serialize this class with:
Test t = new Test();
string s = JsonConvert.SerializeObject( t );
I get the error Error getting value from 'y' on 'Test'
. The same happens if y is const.
My theory is that static and const values are stored somewhere special in memory, and for some reason the Json serializer dies trying to access them. That's entirely a hunch though, and I see nothing in the C# Reference for Static that's of any help. I'm relatively new to C# - and this is really a curiosity question more than anything at this point.
NET objects as JSON (serialize) To write JSON to a string or to a file, call the JsonSerializer. Serialize method. The JSON output is minified (whitespace, indentation, and new-line characters are removed) by default.
JSON is language independent and because of that, it is used for storing or transferring data in files. The conversion of data from JSON object string is known as Serialization and its opposite string JSON object is known as Deserialization.
In Java, serialization is a concept using which we can write the state of an object into a byte stream so that we can transfer it over the network (using technologies like JPA and RMI). But, static variables belong to class therefore, you cannot serialize static variables in Java.
Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.
It could certainly serialize the static variable if it wanted to. Serialization is done by inspecting objects and types with the Reflection APIs, and those APIs allow you to do "anything" -- there is no technical reason these values cannot be serialized.
There is, however, a logical reason not to support this by default: it doesn't make much sense. You are serializing an instance, and static
or const
members are not logically part of an instance but of the class as a whole.
That said, you can still serialize static
member if it's a property:
[JsonProperty]
public static int y { get; set; } // this will be serialized
And of course you can completely override the serializer's behavior by creating a custom JsonConverter
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With