Comments (4)
Anchors are supported by the library. The type discriminators are new and may be the culprit. I’ll try and take a look in a bit. Can you try doing it without the type discriminator and see if you get the same error?
from yamldotnet.
Anchors are supported by the library. The type discriminators are new and may be the culprit. I’ll try and take a look in a bit. Can you try doing it without the type discriminator and see if you get the same error?
What do you mean without the type discriminator do you mean without the extension method here:
.WithTypeDiscriminatingNodeDeserializer(options =>
{
options.AddKeyValueTypeDiscriminator<IExample>("type",
("Word", typeof(WordExample)),
("Number", typeof(NumberExample)));
})
because if so no I don't get the same exception:
**(Line: 5, Col: 5, Idx: 66) - (Line: 5, Col: 5, Idx: 66): Exception during deserialization
System.InvalidOperationException: Failed to create an instance of type 'Experiments.Tests.Models.IExample'.
---> System.MissingMethodException: Cannot dynamically create an instance of type 'Experiments.Tests.Models.IExample'. Reason: Cannot create an instance of an interface.
at System.RuntimeType.ActivatorCache..ctor(RuntimeType rt)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean wrapExceptions)
at YamlDotNet.Serialization.ObjectFactories.DefaultObjectFactory.Create(Type type)
--- End of inner exception stack trace ---
at YamlDotNet.Serialization.ObjectFactories.DefaultObjectFactory.Create(Type type)
at YamlDotNet.Serialization.NodeDeserializers.ObjectNodeDeserializer.Deserialize(IParser parser, Type expectedType, Func`3 nestedObjectDeserializer, Object& value)
at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)**
Which I'm assuming that means it is the type discriminator?
from yamldotnet.
What I was meaning was this, which results in the same exception, skipping the TypeDescriminator
var yaml = @"example_word: &example_word 'AN EXAMPLE WORD'
examples:
- type: Number
value: 1337
- type: Word
value: *example_word
";
var deserializer = new DeserializerBuilder()
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.IgnoreUnmatchedProperties()
.Build();
var o = deserializer.Deserialize<ExampleConfig>(yaml);
Console.WriteLine(o);
public class ExampleConfig
{
public List<Example> Examples { get; set; }
}
public class Example
{
public string Type { get; set; }
public string Value { get; set; }
}
When I change ExampleConfig
to include public string ExampleWord { get; set; }
the above code works as well as your code.
With that, I believe anchors/aliases only work when the anchor is assigned to an object.
I'm going to look into why it needs to be assigned to something and see if I can resolve that issue. I'll keep you updated.
from yamldotnet.
Ok, I think I figured out why it needs to be a property in a class, it needs to know the type of object that it needs to deserialize to.
You will need to have ExampleWord
as a property in whatever class your anchor is in and ignoring that field just isn't going to work, not without a major refactoring of the deserializers. At least, that's what I was able to tell from my testing and looking at the code.
If you don't want that property public, you can mark it as private and use the IncludeNonPublicProperties()
method on the builder. Like this
var deserializer = new DeserializerBuilder()
.WithNamingConvention(UnderscoredNamingConvention.Instance)
.WithTypeDiscriminatingNodeDeserializer(options =>
{
options.AddKeyValueTypeDiscriminator<IExample>("type",
new Dictionary<string, Type> {
{ "Word", typeof(WordExample) },
{ "Number", typeof(NumberExample) }
});
})
.IncludeNonPublicProperties()
.Build();
var o = deserializer.Deserialize<ExampleConfig>(yaml);
Console.WriteLine(o);
public sealed class ExampleConfig
{
#pragma warning disable IDE0051 // Remove unused private members
private string? ExampleWord { get; set; }
#pragma warning restore IDE0051 // Remove unused private members
public List<IExample> Examples { get; set; } = new List<IExample>();
}
I'm going to close this issue since I've given you the answer to the problem.
from yamldotnet.
Related Issues (20)
- Parser does not recognize quoted keys HOT 2
- Can't handle anchored lists HOT 11
- Cannot parse YAML file, (Line: 2, Col: 3, Idx: 6) - (Line: 2, Col: 3, Idx: 6): Exception during deserialization HOT 2
- Do you think it's useful to add some F# examples along with the C# code? HOT 4
- Schema validation support HOT 10
- Unwanted conversion from a string to a numeric value HOT 1
- missing `IDeserializer object? Deserialize(string input)` method HOT 2
- How to Serialize an object with Directives, start and end marks (---, ...)? HOT 2
- How to forcefully interpret as an array with implied key HOT 3
- YamlStream.Load with JSON with emojis (even escaped) fails: "While scanning a quoted scalar, found invalid Unicode character escape code." HOT 13
- OmitDefaults doesn't work for properties of sub-objects HOT 14
- DateTime fails Serialization/Deserialization roundtrip when JsonCompatible is on HOT 5
- Serialization/Deserialization vs strings with funny characters HOT 8
- How do I use this with multiple documents of arbitrary types? HOT 3
- YamlMember Alias usage HOT 4
- RobiniaDocs API Explorer HOT 1
- Add support for including types defined in another assembly in static code generation HOT 1
- Static code generation fails to generate code for Dictionary and List which use Array values
- Type descriminator keys and casing HOT 4
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from yamldotnet.