Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API and [Serializable] class

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?

like image 358
Malako Avatar asked Nov 07 '12 06:11

Malako


People also ask

What is serialization in Web API?

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.

Does Web API support BSON?

NET client app. Web API 2.1 introduces support for BSON.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings.


1 Answers

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.

like image 126
Youssef Moussaoui Avatar answered Sep 21 '22 13:09

Youssef Moussaoui