I have a class that is marked with [Serializable]. When i return it from the Web API the field names are all funky.
Normally the JSON returned is
[{"OrderId":797 ...
JSON returned when using [Serializable]
[{"<OrderId>k__BackingField":797 ...
I wan't to mark it serializable to use a BinaryFormatter for caching. Is there any other way than to write a custom serializer or to make a twin class that is not serializable and write monkey code to "cast" between the two?
So, serialization converts the object into a shareable format. With serialization, we can transfer objects: Between client and server via REST APIs or GRPC. Over the network for messaging systems like Kafka or RabbitMQ. Through firewalls as JSON or XML strings.
NET client app. Web API 2.1 introduces support for BSON.
SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings.
You just need this one-liner to get Json.NET to ignore the [Serializable] semantics again:
((DefaultContractResolver)config.Formatters.JsonFormatter.SerializerSettings.ContractResolver).IgnoreSerializableAttribute = true;
A better solution for you might be to get rid of [Serializable] altogether, stop using BinaryFormatter, and use a different serializer instead to do whatever caching you want to do, like the Json.NET serializer for example.
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