WCF & JSON: Serialize long as string

不问归期 提交于 2019-12-25 11:59:11

问题


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.


回答1:


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....



来源:https://stackoverflow.com/questions/13700925/wcf-json-serialize-long-as-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!