How can I make DataContractJsonSerializer serialize an object as a string?

谁说我不能喝 提交于 2019-11-30 18:31:52

In this case it looks like you don't really want JSON, you want a string representation. In that case I would create an interface like this:

interface IStringSerialized
{
    String GetString();
}

Implement this interface on your ID type (and all other types that have similar requirements).

[Serializable]
class ID : IStringSerialized
{
    private Guid _value;

    public static explicit operator ID(Guid id)
    {
        return new ID { _value = id };
    }

    public static explicit operator Guid(ID id)
    {
        return id._value;
    }

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

Then modify your serialization method to handle these special cases:

private static string ToJson<T>(T data)
{
    IStringSerialized s = data as IStringSerialized;

    if (s != null)
        return s.GetString();

    DataContractJsonSerializer serializer 
                = new DataContractJsonSerializer(typeof(T));

    using (MemoryStream ms = new MemoryStream())
    {
        serializer.WriteObject(ms, data);
        return Encoding.Default.GetString(ms.ToArray());
    }
}

Try using the JavaScriptSerializer Class it will prevent the key, value bloat issue.

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