使用ServiceStack JsonSerializer反序列化包含Dictionary属性的类型

时间:2013-02-05 21:12:12

标签: .net serialization deserialization servicestack msgpack

下面的代码段显示了我可以实现此目的的两种方法。第一个使用MsgPack,第二个测试使用ServiceStack's JSONSerializer。第二个更有利,因为ServiceStack.Text JSONSerializer在我正在工作的整个项目中使用。

为什么使用Dictionary< Street,HashSet< int>>时,第二个测试失败了?

[TestFixture]
public class NeighbourhoodTests
{
    private Neighbourhood _myNeighbourhood;
    private Street _street;

    [SetUp]
    public void SetupOnEachTest()
    {
        _street = new Street() { Name = "Storgate" };
        _myNeighbourhood = SetupMyNeighbourhood(_street);
    }

    private static Neighbourhood SetupMyNeighbourhood(Street street)
    {
        var myNeighbourhood = new Neighbourhood();
        myNeighbourhood.Addresses = new Dictionary<Street, HashSet<int>>();

        myNeighbourhood.Addresses.Add(street, new HashSet<int>(new[] { 1, 2, 3, 4 }));
        myNeighbourhood.LocalCouncilName = "Stavanger";
        myNeighbourhood.RegionName = "Rogaland";
        return myNeighbourhood;
    }

    [Test]
    public void TestNeighbourhoodClass_OnMsgPackDeserialization_AddressesShouldEqualOriginalInput()
    {
        ObjectPacker packer = new ObjectPacker();
        var packedMessageBytes = packer.Pack(_myNeighbourhood);
        var unpackedMessage = packer.Unpack(packedMessageBytes);

        Assert.That(unpackedMessage.RegionName, Is.EqualTo("Rogaland"));
        Assert.That(unpackedMessage.Addresses, Is.Not.Empty);
        Assert.That(unpackedMessage.Addresses.Keys.Any(key => key.Name.Equals(_street.Name)));
    }

    [Test]
    public void TestNeighbourhoodClass_OnServiceStackJsonTextDeserialization_AddressesShouldEqualOriginalInput()
    {
        string serialisedMessage = JsonSerializer.SerializeToString(_myNeighbourhood);
        var deserializedMessage = JsonSerializer.DeserializeFromString(serialisedMessage);

        Assert.That(deserializedMessage.RegionName, Is.EqualTo("Rogaland"));
        Assert.That(deserializedMessage.Addresses, Is.Not.Empty);
        Assert.That(deserializedMessage.Addresses.Keys.Any(key => key.Name.Equals(_street.Name)));
    }
}

public class Neighbourhood
{
    public Dictionary<Street, HashSet<int>> Addresses { get; set; }
    public string LocalCouncilName { get; set; }
    public string RegionName { get; set; }
}

1 个答案:

答案 0 :(得分:1)

Aaah感谢@mortenrøgenes-证明我必须将Neighborhood类的Addresses属性包装成它自己的类型:

public class Addresses
{
    public Street Street{ get; set; }
    public HashSet<int> HouseNumbers { get; set; }
}
public class Neighbourhood
{
    public Addresses { get; set; }
    public string LocalCouncilName { get; set; }
    public string RegionName { get; set; }
}

这样ServiceStack JSONSerializer可以工作,测试就会通过。