gpt4 book ai didi

c# - 反序列化 List 对象

转载 作者:数据小太阳 更新时间:2023-10-29 02:32:20 27 4
gpt4 key购买 nike

我正在尝试将 XML 反序列化为对象,但我遇到了一种情况。任何人都可以在这里帮助我。

XML:

<?xml version="1.0" ?>
<Level>
<Warp_Blocks>
<Warp_Block>
<Block row="7" col="7" />
<Block row="2" col="7" />
</Warp_Block>
<Warp_Block>
<Block row="4" col="4" />
<Block row="3" col="7" />
</Warp_Block>
</Warp_Blocks>
</Level>

代码:

  [XmlRoot("Level")]
public class LData
{
[XmlArray("Warp_Blocks")]
[XmlArrayItem("Warp_Block",typeof(WarpBlock),IsNullable = false)]
public List<WarpBlock> WarpBlocks;
}
public class LBlock
{
[XmlAttribute("row")]
public int row;
[XmlAttribute("col")]
public int col;
}
public class WarpBlock
{
[XmlArray("Warp_Block")]
[XmlArrayItem("Block",typeof(LBlock),IsNullable= false)]
public List<LBlock> WarpBlocks;

public WarpBlock()
{
WarpBlocks = new List<LBlock>();
}
}

我能够反序列化到一个级别,即我得到一个 Item 对象列表,但单个 Item 对象不包含 Block 对象列表。我在这里做错了什么?

最佳答案

将您的 LData 类更改为此:

[XmlRoot("Level")]
public class LData
{
[XmlElement("Warp_Blocks")]
public List<WarpBlock> WarpBlocks;
}

编辑:
我不知道为什么它不读取您的第二个 Warp_Block。我认为唯一可能的原因可能是您正在做与您在问题中发布的内容不同的事情。这是完整的示例:

[XmlRoot("Level")]
public class LData
{
[XmlElement("Warp_Blocks")]
public List<WarpBlock> WarpBlocks;
}
public class LBlock
{
[XmlAttribute("row")]
public int row;
[XmlAttribute("col")]
public int col;
}
public class WarpBlock
{
[XmlArray("Warp_Block")]
[XmlArrayItem("Block", typeof(LBlock), IsNullable = false)]
public List<LBlock> WarpBlocks;

public WarpBlock()
{
WarpBlocks = new List<LBlock>();
}
}
public class Program
{
public static void Main()
{
string test =
"<?xml version=\"1.0\" ?>" +
"<Level>" +
" <Warp_Blocks>" +
" <Warp_Block>" +
" <Block row=\"7\" col=\"7\" />" +
" <Block row=\"2\" col=\"7\" />" +
" </Warp_Block>" +
" <Warp_Block>" +
" <Block row=\"4\" col=\"4\" />" +
" <Block row=\"3\" col=\"7\" />" +
" </Warp_Block>" +
" </Warp_Blocks>" +
"</Level>";

byte[] byteArray = Encoding.ASCII.GetBytes(test);
MemoryStream stream = new MemoryStream(byteArray);

XmlSerializer s = new XmlSerializer(typeof (LData));
LData data = (LData) s.Deserialize(stream);

foreach (var a in data.WarpBlocks)
foreach (var b in a.WarpBlocks)
Console.WriteLine(b.row + ", " + b.col);

Console.ReadKey();
}
}

它正确输出:

7, 7
2, 7
4, 4
3, 7

关于c# - 反序列化 List<ArrayList> 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5016558/

27 4 0