序列化/反序列化命令对象

时间:2013-03-07 09:20:38

标签: c# serialization command-pattern

我正在尝试将命令对象序列化(以后反序列化)为字符串(最好使用JavaScriptSerializer)。我的代码编译,但是当我序列化我的命令对象时,它返回一个空的Json字符串,即“{}”。代码如下所示。

目的是序列化命令对象,将其放入队列中,然后在以后对其进行反序列化,以便执行它。如果解决方案可以用.NET 4实现,那就更好了。

的ICommand

public interface ICommand
{
    void Execute();
}

命令示例

public class DispatchForumPostCommand : ICommand
{
    private readonly ForumPostEntity _forumPostEntity;

    public DispatchForumPostCommand(ForumPostEntity forumPostEntity)
    {
        _forumPostEntity = forumPostEntity;
    }

    public void Execute()
    {
        _forumPostEntity.Dispatch();
    }
}

实体

public class ForumPostEntity : TableEntity
{
    public string FromEmailAddress { get; set; }
    public string Message { get; set; }

    public ForumPostEntity()
    {
        PartitionKey = System.Guid.NewGuid().ToString();
        RowKey = PartitionKey;
    }

    public void Dispatch()
    {
    }
}

空字符串示例

public void Insert(ICommand command)
{
   // ISSUE: This serialization returns an empty string "{}".
   var commandAsString = command.Serialize();
}

序列化扩展方法

public static string Serialize(this object obj)
{
    return new JavaScriptSerializer().Serialize(obj);
}

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:1)

您的DispatchForumPostCommand类没有要序列化的属性。添加公共属性以序列化它。像这样:

public class DispatchForumPostCommand : ICommand {
    private readonly ForumPostEntity _forumPostEntity;

    public ForumPostEntity ForumPostEntity { get { return _forumPostEntity; } }

    public DispatchForumPostCommand(ForumPostEntity forumPostEntity) {
        _forumPostEntity = forumPostEntity;
    }

    public void Execute() {
        _forumPostEntity.Dispatch();
    }
}

我现在得到以下作为序列化对象(为了测试目的,我删除了TableEntity的继承):

{"ForumPostEntity":{"FromEmailAddress":null,"Message":null}}

如果你想反序列化对象,那么你需要为属性添加公共setter,否则反序列化器将无法设置它。