Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert int to bool on json deserialization

Tags:

json

c#

asp.net

I have a class that i uses JavaScriptSerializer.Deserialize<class>

One of the properties i get from the UI is an int (0 or 1). Is there any way to change the getter/setter on the property in c# so it understands that it should return true or false based on the value? Or do i need another property that checks the int prop? Thanks

like image 859
Johan Avatar asked Oct 23 '22 10:10

Johan


People also ask

Can you convert an int to a bool?

To convert integer to boolean, initialize the bool value with integer. Now, use the == operator to compare the int with a value and if there is a match, TRUE is returned.

How do I deserialize a JSON file?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

What is Deserializing a JSON?

The process whereby a lower-level format (e.g. that has been transferred over a network, or stored in a data store) is translated into a readable object or other data structure. In JavaScript, for example, you can deserialize a JSON string to an object by calling the function JSON. parse() .

How does Jackson serialize boolean?

By default, Jackson serializes the boolean fields to JSON true and false values. If we want the default serialization to produce numbers 1 and 0 for boolean fields then we can use @JsonFormat annotation at field level. public class Employee { ... @JsonFormat(shape = JsonFormat.


1 Answers

The best way would be to create your own JavaScriptConverter which can be used to handle your object and convert between different data types. Override the serialize/deserialize methods and parse the format as you wish.

Here's a link to a previous answer I wrote which implements the JavaScriptConverter, showing you how you'd pass it to the JavaScriptSerializer object: https://stackoverflow.com/a/4999004/298053

like image 125
Brad Christie Avatar answered Oct 27 '22 10:10

Brad Christie