gpt4 book ai didi

java - YamlDotNet:如何处理!!set

转载 作者:行者123 更新时间:2023-11-30 07:55:21 29 4
gpt4 key购买 nike

我正在尝试反序列化一些在序列化 Java HashSet 时在 SnakeYaml 创建的字符串中设置了 !! 的 YAML。不同的泛型类型被序列化,例如 HashSet 和自定义类型 HashSet。

示例 YAML:

holidays: !!set
? DDMMYYYY: 25/12/2042
MMDDYYYY: 12/25/2042
date:
chronology: &id001
calendarType: iso8601
id: ISO
dayOfMonth: 25
dayOfWeek: THURSDAY
dayOfYear: 359
era: CE
leapYear: false
month: DECEMBER
monthValue: 12
year: 2042
serialValue: 52225
: null

我最初遇到异常:

Additional information: Could not load file or assembly '2002:set' or one of its dependencies. The system cannot find the file specified.

为了解决这个问题,我将标签映射注册到解串器:

{"tag:yaml.org,2002:set", typeof (HashSet<object>)}

然后我得到异常:

A first chance exception of type 'YamlDotNet.Core.YamlException' occurred in YamlDotNet.dll Additional information: (Line: 4, Col: 23, Idx: 108) - (Line: 5, Col: 9, Idx: 122): Expected 'SequenceStart', got 'MappingStart' (at Line: 4, Col: 23, Idx: 108).

我本以为处理集是 YAML 的一个非常常见的要求,但我不知道如何解决这个问题。

谁能告诉我如何处理吗?

最佳答案

问题是 HashSet<T>不实现IDictionary<TKey, TValue> ,然后反序列化为序列而不是映射。

您将需要创建自己的集合实现,也许可以通过扩展 HashSet<T>并实现IDictionary<T, object>像这样:

public class YamlSet<T> : HashSet<T>, IDictionary<T, object>
{
void IDictionary<T, object>.Add(T key, object value)
{
Add(key);
}

object IDictionary<T, object>.this[T key]
{
get
{
throw new NotImplementedException();
}
set
{
Add(key);
}
}
// ...
}

IDictionary<T, object>还有更多成员您必须实现这些,但这些是使反序列化工作所必需的。

See a fully working example here

关于java - YamlDotNet:如何处理!!set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32757084/

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