gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:50:03 24 4
gpt4 key购买 nike

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

为什么下面的第二个测试在使用 Dictionary > 时失败了?

[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; }
}

最佳答案

啊啊感谢@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 就会工作并且测试会通过。

关于.net - 使用 ServiceStack JsonSerializer 反序列化包含 Dictionary 属性的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14716979/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com