Comments (6)
I also had the same issue and I found a solution that suitable for me. If little bit correct the condition in the code sample provided by Antoine we can ignore values in YAML document that are quoted and should not be converted to simple types such as bool or int.
So, if (scalar != null)
we should replace on if (scalar != null && !scalar.IsQuotedImplicit)
and all works fine!
from yamldotnet.
Hi,
The behavior that you describe is what the YAML specification 1.2 mandates. Using the JSON schema or the Core schema you would get the desired behavior. However, that support is still work in progress. For now, you can still achieve what you want by creating a new type resolver:
public class ScalarNodeTypeResolver : INodeTypeResolver
{
bool INodeTypeResolver.Resolve(NodeEvent nodeEvent, ref Type currentType)
{
if (currentType == typeof(object))
{
var scalar = nodeEvent as Scalar;
if(scalar != null)
{
// Expressions taken from https://github.com/aaubry/YamlDotNet/blob/feat-schemas/YamlDotNet/Core/Schemas/JsonSchema.cs
if(Regex.IsMatch(scalar.Value, @"^(true|false)$", RegexOptions.IgnorePatternWhitespace)
{
currentType = typeof(bool);
return true;
}
if(Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* )$", RegexOptions.IgnorePatternWhitespace)
{
currentType = typeof(int);
return true;
}
if(Regex.IsMatch(scalar.Value, @"^-? ( 0 | [1-9] [0-9]* ) ( \. [0-9]* )? ( [eE] [-+]? [0-9]+ )?$", RegexOptions.IgnorePatternWhitespace)
{
currentType = typeof(float);
return true;
}
// Add more cases here if needed
}
}
return false;
}
}
Next, you just need to register it on the deserializer:
var deserializer = new Deserializer();
deserializer.TypeResolvers.Add(new ScalarNodeTypeResolver());
var result = deserializer.Deserialize(stream);
You should get the result that you expected: [ 1, 233, "1.0.0.5" ]
I hope this helps you.
from yamldotnet.
Hello,
There is support to deserialize YAML documents into objects, as well as serializing them back to YAML. You need to use the Deserializer class.
The YamlNode et al present an object model that maps to the document structure, similar to XmlNode. That's why serialization / deserialization is independent of these.
Unfortunately, the examples are lacking, but take a look at the unit tests in https://github.com/aaubry/YamlDotNet/blob/master/YamlDotNet.Test/Serialization/SerializationTests.cs.
Please reopen the issue if you have further questions. Thanks.
from yamldotnet.
Hi Antoine,
Thank you very much for your help.
I have one more question.
Part of my yaml file content looks like this:
"- - 1
- 233
- 1.0.0.5"
I am deserializing it using this command:
var stream = Yaml.StreamFrom("my_file.yaml");
var result = Deserializer.Deserialize(stream);
And I get this result:
['1', '233', '1.0.0.5']
As you can see all three objects in list are of type string.
Is there a way to implicitly convert first two objects into integer (int) type without explicitly specifying their types or without using tags in my yaml file.
If there is no way to do this do you have in plan to implement that kind of deserialization.
This is important to me because I have to read files which structure I don't know in advance so I can't explicitly provide types in source code when deserializing scalar nodes.
Best regards,
Vladimir
from yamldotnet.
Hi Antoine,
This is just what I needed.
Thank you very much for your help.
Regards,
Vladimir
from yamldotnet.
Hi Antoine,
There is another problem, so I need your help again.
I have input yaml file that looks like this:
- - 2
- '6.0'
- false
- - 3
- '6.1'
- false
I use YamlDotNet to read this input file and immediately writes it to another file without changing the content.
Content of the output file looks like this:
- - 2
- 6.0
- false
- - 3
- 6.1
- false
As you can see there is difference between input and output file, i.e., in output file are missing single quotes around 6.0 and 6.1 strings.
Code that I am using for reading and writing to file is this:
// Reading form input file
string path = @"C:\input.yaml";
var fs = new System.IO.FileStream(path, System.IO.FileMode.Open);
var stream = new System.IO.StreamReader(fs);
var deserializer = new Deserializer();
var result = deserializer.Deserialize(stream);
// Writing to output file
var serializer = new Serializer();
System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\output.yaml");
serializer.Serialize(file, result);
file.Close();
I tried to use all options from enum SerializationOptions, but did not achieve the desired goal (I wanted to completely keep unchanged the content of the input file).
Am I doing something wrong or am I missing some options when serializing and writing to output file?
Regards,
Vladimir
P.S. I have attached screenshot of the input and output files because there are bullets appearing in examples that I pasted in this comment.
from yamldotnet.
Related Issues (20)
- Polymorphic deserialization - Alias $example_word cannot precede anchor declaration HOT 4
- 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
- Enum serialization behavior changed after #856 HOT 1
- Property 'access-points' not found on type ... HOT 4
- Disable serialization for specific types
- The serializer serialitzes wrong the string arrays HOT 3
- Incorrect handling of carriage return `\r` and tab `\t` HOT 6
- Add quotes for strings on model serialization HOT 3
- Order for inheritance HOT 2
- Add new line between items
- yaml.Documents[].RootNode is YamlScalarNode instead of YamlMappingNode in VS2022 console project HOT 6
- Deserializing multiple documents does not work HOT 2
- Problem Deserializing a list of player HOT 5
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.