Search code examples
jsonwcfwcf-data-services

WCF & JSON: Serialize long as string


I have a wcf data service and a normal rest wcf service. Both services return the same entity object.

[DataContract]
public partial class MyEntity
{
    #region Primitive Properties
    [DataMember]
    public virtual long ID
    {
        get;
        set;
    }
    ....

The normal rest wcf service uses the following service contract:

[ServiceContract]
public interface MyService
{
    [OperationContract]
    [WebGet(UriTemplate="MyEntity/{id}",ResponseFormat=WebMessageFormat.Json)]
    public MyEntity GetMyEntity(string id)
}

while the wcf data service returns the long value as string:

{{"id": ... ,"uri": ... ,"type":"Model.MyEntity"},"ID":"865176660053852161"}

the MyService ServiceContract returns the long as number:

{ "ID":865176660053852161 }

Seems like the wcf data service and the "normal" rest service use two different kind of serialization mechanisms.

Problem is: My client app uses JavaScript and can therefore not handle 64bit numbers. I would have expected, that the "normal" rest service also would return 64bit numbers as string.

  • Where can I convert the number during the serialiuation/deserialization process to a string?
  • In case anyone knows: Why is the behaviour different between wcf data services / rest based wcf?

For consistency I would prefer a conversion during the serialization process on the serverside, but I don't know if this is feasible.


Solution

  • My workaround now is to adapt the t4 template for the poco generation, so that the entity objects are genereated like this:

    [DataContract]
    public partial class MyEntity
    {
        #region Primitive Properties
    
        public virtual long ID
        {
            get { return _iD; }
            set { _iD = value; _iDStr = value.ToString(); }
        }
    
        [DataMember(Name="ID")]
        private string _iDStr;
        private long _iD;
    
        ...
    

    This will return the ID as string in the WCF response, while the entity framework still works with the long value....