JavaScriptSerializer and ValueTypes (struct)

716 views Asked by At

For a project i've created several struct in C#. The probject itself is a ASP.Net MVC 2 project.

snip:

struct TDummy
{
    private char _value;

    public TDummy(char value)
    {
         this._value = value; // Restrictions
    }
}

I created this because I needed to restrict a char-variable to a specific number of values. (I could have created an Enum, but these values are also used in the database, and then i would still need to convert them)

Now i need to create a JsonResult, like

return Json(new { Value = new TDummy('X') });

But when I do this, I get a result of:

{"Value":{}}

I expected to get a result of

{"Value":"X"}

I've tried several things, like TypeConverter (CanConvertTo(string)), Custom Type Serializer (JavaScriptSerializer.RegisterConverters()), but either they don't work or they must return a 'Complex' json-object.

{"Value":{"Name":"Value"}}

Any thoughts on this?
I want to serialize a value-type as a value...

1

There are 1 answers

0
Debbus On

If anyone is interested, i've create a small demo (console app) to illustrate this:

public struct TState
{
   public static TState Active = new TState('A');
   public static TState Pending = new TState('P');

   private char _value;

   public TState(char value)
   {
      switch (value)
      {
         case 'A':
         case 'P':
            this._value = value;  // Known values
            break;
         default:
            this._value = 'A';    // Default value
            break;
      }
   }

   public static implicit operator TState(char value)
   {
      switch (value)
      {
         case 'A':
            return TState.Active;
         case 'P':
            return TState.Pending;
      }
      throw new InvalidCastException();
   }

   public static implicit operator char(TState value)
   {
      return value._value;
   }

   public override string ToString()
   {
      return this._value.ToString();
   }
}

public class Test { public TState Value { get; set; } }

class Program
{
   static void Main(string[] args)
   {
      Test o = new Test();
      o.Value = 'P';               // From Char
      char c = o.Value;            // To Char
      Console.WriteLine(o.Value);  // Writes 'P'
      Console.WriteLine(c);        // Writes 'P'

      JavaScriptSerializer jser = new JavaScriptSerializer();
      Console.WriteLine(jser.Serialize(o));  // Writes '{"Value":{}}'

      Console.ReadLine();
   }
}