質問

I'm attempting to serialize (and later deserialize) a command object to a string (preferably using the JavaScriptSerializer). My code compiles, however when I serialize my command object it returns an empty Json string, i.e. "{}". The code is shown below.

The aim is to serialize the command object, place it in a queue, then deserialize it later so it can be executed. If the solution can be achieved with .NET 4 then all the better.

ICommand

public interface ICommand
{
    void Execute();
}

Command Example

public class DispatchForumPostCommand : ICommand
{
    private readonly ForumPostEntity _forumPostEntity;

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

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

Entity

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()
    {
    }
}

Empty String Example

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

Serialization Extension Method

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

Any help would be appreciated.

役に立ちましたか?

解決

Your DispatchForumPostCommand class has no properties to serialize. Add a public property to serialize it. Like this:

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();
    }
}

I now get the following as the serialized object (I removed the inheritance of TableEntity for testing purposes):

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

If you want to deserialize the object as well, then you will need to add the public setter for the property, else the deserializer will not be able to set it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top